⚠️ This lesson is retired and might contain outdated information.

Use GraphQL with React Query's useQuery

Domitrius Clark
InstructorDomitrius Clark
Share this video with your friends

Social Share Links

Send Tweet

One of React Query's biggest strength is it's flexibility when dealing with asynchronous data. We will take a previously REST based app and plug in graphql-request to use GraphQL within our useQuery

Domitrius Clark: [0:00] This point we've been using a REST API to get our data and return our character list. What if we wanted to use GraphQL instead? Thankfully, React Query doesn't care how we get the data as long as the function returns a promise.

[0:14] Which means we can install something like GraphQL request to get rid of that REST endpoint, stop using fetch, and instead use their request function and pass in the new GraphQL endpoint. We're going to import the request function from graphql-request.

[0:38] Next, we'll define a variable that will hold the description of our query. We'll name that variable SEARCH_CHARACTERS. We'll define our query inside of template literal strings so that our request can read our query. We'll name the query SearchCharacters and we'll be giving it a variable of name which is equal to a non-nullable string.

[0:59] Next we'll work on actually defining the query of characters where we'll actually pass in a filter that is equal to our variable of name. Then we'll get the results, which will give us our character's ID, name, and image.

[1:18] Now we can work on replacing our fetchCharacters function with a new function that will be utilizing the GraphQL endpoint. Now we can clear out our empty function call and replace it with an asynchronous inline function with the same exact arguments before of key and name. We'll define a constant of characters, which will hold on to our awaited GraphQL request.

[1:44] GraphQL requests request function takes in three arguments. Our first one is going to be the GraphQL endpoint. Our second one will be our query constant of SEARCH_CHARACTERS. Then a third one can be any variables that we need to pass in, and for us, that's going to be the name. We'll wrap this function up by returning our characters.

[2:10] Now in our request currently, we're only looking for data.results, but coming down for GraphQL, it will be data.characters.results. Now we can actually go ahead, refresh. Double check to make sure our search is still working. And it is.

[2:27] We can add characters to our favorites, search Morty. If we go back to searching Rick, you'll see we're cached, and it's a quick update.