Step 3: Displaying our Data - aaronpanch/idea-board GitHub Wiki

After Implementing our first type, we have data available to the client. Now we need to feed it to our React components and get it in front of users!

Idea Index Page

The first thing we would like to do is have the ability to display a list of Ideas. If you're a little bhind on getting the server-side of the app completed, you can check out the start-here-client branch for a complete server and client that uses sample data.

  • In the app/javascript/idea_board/components/IdeaIndex.js file you can see our import of sample data:
import ideas from "../sample_ideas";
  • The block of code below iterates over the sample ideas and sends their information to the IdeaCard component.
{ideas.length ? (
  ideas.map(idea => <IdeaCard key={idea.id} {...idea} />)
) : (
  <p className="text-center m-4">There aren't any ideas yet!</p>
)}

Our job is to use an Apollo hook to populate this ideas list. For this, we will use the useQuery react hook provided by Apollo. But first, we need to define our queries so that the hook knows how to ask for the list.

  • Create a file called Ideas.graphql in the components directory. We'll use this file to define our queries. Looking at the IdeaCard component, we can see that the properties it expects to see are id, title, body, votes, voted, author, these properties will map directly to our idea list query.

in Ideas.graphql, add:

query Ideas {
  ideas {
    id
    title
  }
}

Look familiar? That's right, it's exactly the same as the queries we ran in Playground to display the data. It's also worth noting that the shape we ask for defines the shape we receive, so in other components that may not need this much information, we can adjust our query.

  • Now back in the IdeaIndex component, we import our hook with:
import { useQuery } from "@apollo/react-hooks";
  • And the query:
import { Ideas } from "./Ideas.graphql"
  • This allows us to populate our data with:
const { data, loading } = useQuery(Ideas);

Where data is the eventual response from the server, and loading is set to true while the data loads. So simple right!

Now we can guard our view with the loading variable, and assign our idea list to the data we retrieved!

On your own, attempt to use the useMutation add voting to the IdeaCard component.