Getting Lazy
Learn about lazy queries generated by GraphQL Code Generator and use them in a React application.
The generated useAllBooksLazyQuery
function
GraphQL Code Generator created a function named useAllBooksLazyQuery
in our src/generated/graphql.tsx
file.
export function useAllBooksLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<AllBooksQuery, AllBooksQueryVariables>) {const options = {...defaultOptions, ...baseOptions}return Apollo.useLazyQuery<AllBooksQuery, AllBooksQueryVariables>(AllBooksDocument, options);}
This function looks a lot like useAllBooksQuery
, but it uses the word “lazy” a few times. In this lesson, we’ll explore the difference between the useAllBooksQuery
and the useAllBooksLazyQuery
functions. We will use a function like useAllBooksLazyQuery
to search for books that contain a specific word or two in their title
.
Here is what we will have by the end of this lesson.
Working with lazy queries
To find all books, we use the books field. But to find books
by a title, the GraphQL server uses a different field called booksWithTitle
, as shown in the code snippet below:
query {booksWithTitle(title: "React") {title}}
To use this new query in our client, we will remove the allBooksQuery
from the components/Books/index.tsx
...