We've got our server connected to React with Apollo Client. Let's write our first query!

In App.js, we first need to import two things:

// App.js
import { useQuery, gql } from "@apollo/client";

You can tell by that "use" that useQuery is a React hook. The gql import is a really cool function that lets you pass in GraphQL syntax via a tagged template literal (check out this video in my Gatsby course to learn more about tagged template literals).

Next, let's write our query:

// App.js
const HABITS_QUERY = gql`
  query HABITS_QUERY {
    habits {
      id
      description
      points
    }
  }
`;

Note: I've noticed a problem with the Apollo GraphQL VS Code Extension if the server isn't running when you open VS Code to work on this. If you're not getting your autocomplete, try opening the Command Palette (that's command-shift-P on a Mac, control-shift-P on Windows), typing "Apollo," and selecting the option "Apollo GraphQL: Reload schema." That fixed it for me and you should again have autocomplete and intellisense for your GraphQL queries.

We're ready to use our query in the useQuery hook, which will give back to us our data in addition to a loading or error state (which includes the error message). Here's the finished code for the App component:

// App.js
function App() {
  const { data, loading, error } = useQuery(HABITS_QUERY);

  if (loading) {
    return <p>loading...</p>;
  }

  if (error) {
    return <p>Ruh roh! {error.message}</p>;
  }

  return (
    <>
      <h2>Habits</h2>
      <ul>
        {data.habits.map((habit) => {
          return (
            <li key={habit.id}>{habit.description}</li>
          );
        })}
      </ul>
    </>
  );
}

In the next video, we'll fire up the browser and take a look at our results.

 

I finished! On to the next chapter