This video is available to students only

How to Replace useQuery and useMutation With Apollo Hooks

With the Apollo client available everywhere in our app, we'll replace the use of the custom useQuery and useMutation Hooks with the variations provided to us from the React Apollo library.

React Apollo Hooks#

📝 This lesson's quiz can be found - here.
🗒️ Solutions for this lesson's quiz can be found - here.
📃 Grab a cheatsheet describing how React Apollo's useQuery Hook can be used - here.
📃 Grab a cheatsheet describing how React Apollo's useMutation Hook can be used - here.

We have the Apollo client created and available everywhere in our app. Let's see how we can import and use the Hooks from React Apollo in our <Listings> component.

In the <Listings> component, we'll now import the useQuery and useMutation Hooks from the React Apollo library instead of our own local src/lib/ folder.

We'll observe that the use of useQuery and useMutation in the <Listings> component doesn't throw any errors except for perhaps in how we pass in the GraphQL document nodes. That is because we've built our custom useQuery and useMutation Hooks to resemble very closely with how the Hooks from React Apollo work!

Here's a summary of how React Apollo's useQuery and useMutation Hooks behave.

  1. The useQuery and useMutation Hooks take two arguments, the query or mutation in question and an options object.

  2. The useQuery and useMutation Hooks accept two type variables, one to represent the shape of data to be returned and the other to represent the shape of variables that can be passed in.

  3. The useQuery Hook returns a series of fields within an object recognized as the QueryResult. data, loading, error, and a refetch() function are some of the fields within the QueryResult. The QueryResult object also returns a bunch of other fields like the Apollo client itself, the networkStatus of the request, a fetchMore() function, and so on.

  4. The useMutation Hook returns a tuple of two values. The first value being the mutation function itself and the second value being the mutation result values which are similar to the result returned in useQuery.

Though the way we've used our custom useQuery and useMutation Hooks mimic that of React Apollo, there are still a few changes we'll need to make.

gql#

The first change we'll make is how we pass in the GraphQL document nodes to our query and mutation requests. With our simple server.fetch() function, we were able to construct and use GraphQL documents that are strings. The Hooks in React Apollo expect our GraphQL documents to be constructed as trees.

We can have our GraphQL documents be created as abstract trees with the help of the gql template tag just like we've seen in our Node server application. The gql template tag is available to us from the apollo-boost package.

Start a new discussion. All notification go to the author.