Queries: Loading Links

Preparing the React components

The first piece of functionality you’ll implement in the app is loading and displaying a list of Link elements. You’ll walk up our way in the React component hierarchy and start with the component that’ll render a single link.

This is a simple React component that expects a link in its props and renders the link’s description and url. Easy as pie! 🍰

Next, you’ll implement the component that renders a list of links.

Here, you’re using local mock data for now to make sure the component setup works. You’ll soon replace this with some actual data loaded from the server - patience, young Padawan!

Run the app to check if everything works so far! The app should now display the two links from the linksToRender array:

Writing the GraphQL query

Next you’ll load the actual links that are stored in the database. The first thing you need to do for that is define the GraphQL query you want to send to the API.

Here is what it looks like:

query FeedQuery {
  feed {
    links {
      id
      createdAt
      description
      url
    }
  }
}

You could now simply execute this query in a Playground (against the application schema) and retrieve the results from your GraphQL server. But how can you use it inside your JavaScript code?

Queries with Apollo Client

When using Apollo, you’ve got two ways of sending queries to the server.

The first one is to directly use the query method on the ApolloClient directly. This is a very direct way of fetching data and will allow you to process the response as a promise.

A practical example would look as follows:

client.query({
  query: gql`
    query FeedQuery {
      feed {
        links {
          id
        }
      }
    }
  `
}).then(response => console.log(response.data.allLinks))

A more idiomatic way when using React however is to use Apollo’s higher-order component graphql to wrap your React component with a query.

With this approach, all you need to do when it comes to data fetching is write the GraphQL query and graphql will fetch the data for you under the hood and then make it available in your component’s props.

In general, the process for you to add some data fetching logic will be very similar every time:

  1. write the query as a JavaScript constant using the gql parser function
  2. use the graphql container to wrap your component with the query
  3. access the query results in the component’s props

What’s going on here?

  1. First, you create the JavaScript constant called FEED_QUERY that stores the query. The gql function is used to parse the plain string that contains the GraphQL code (if you’re unfamililar with the backtick-syntax, you can read up on JavaScript’s tagged template literals).
  2. Now you define the actual GraphQL query. FeedQuery is the operation name and will be used by Apollo to refer to this query under the hood. (Also notice the # which denotes a GraphQL comment).
  3. Finally, you’re using the graphql container to “wrap” the LinkList component with the FEED_QUERY. Note that you’re also passing an options object to the function call where you specify the name to be feedQuery. This is the name of the prop that Apollo injects into the LinkList component. If you didn’t specify it here, the injected prop would be called data by default.

Awesome, that’s all your data fetching code, can you believe that?

You can now finally remove the mock data and render actual links that are fetched from the server.

Let’s walk through what’s happening in this code. As expected, Apollo injected a new prop into the component called feedQuery. This prop itself has 3 fields that provide information about the state of the network request:

  1. loading: Is true as long as the request is still ongoing and the response hasn’t been received.
  2. error: In case the request fails, this field will contain information about what exactly went wrong.
  3. feed: This is the actual data that was received from the server. It has the links property which represents a list of Link elements.

In fact, the injected prop contains even more functionality. You can read more in the documentation.

That’s it! Go ahead and run yarn start again. You should see the exact same screen as before.

Note: If the browser on http://localhost:4000 only says error and is empty otherwise, you probably forgot to have your server running. Note that for the app to work the server needs to run as well - so you have two running processes in your terminal: One for the server and one for the React app. To start the server, navigate into the server directory and run yarn start.

Unlock the next chapter
What's the idiomatic way for loading data with React & Apollo?
Using a higher-order component called 'graphql'
Using the 'query' method on ApolloClient
Using 'fetch' and putting the query in the body of the request
Using XMLHTTPRequest and putting the query in the body of the request