How to create a quick search component using Apollo lazy query
Marcin Kwiatkowski /
When React renders a component that calls the useQuery hook, the Apollo Client runs the query automatically but sometimes you need to query for data on some event. A great case is a quick search component that allows users to search for products in an eCommerce store.
There is a useLazyQuery hook that returns a query function. You can use this function wherever you want, and when you fire it, Apollo will execute a query for you.
When would you use lazy queries?
Typically custom Apollo's hook useQuery is used when you want to query data. That kook is called when React mounts and renders the component, and Apollo Client automatically executes a query then.
What to do when you want to call query manually thought? For instance, when a user clicks on a specific button, or if you're running a query in a useEffect function?
Lazy queries for the rescue!
In that case, you can use the useLazyQuery hook. As I mentioned earlier, It's pretty the same as useQuery with one exception. When useLazyQuery is called, it does not immediately execute its associated query.
Instead, it returns a function in its result tuple that you can call whenever you're ready to execute the query.
On the other hand, the useLazyQuery hook is ideal for executing queries in response to different events, such as user actions. Whenever the useLazyQuery command occurs, the application will not immediately run any queries. You need to trigger a query manually.
I define two states there: isValid and searchQuery, and I pass them to the child component. I check the length of the value entered by a user in the search input, and if the length is higher than 3, I send the query.
Create a new component called QuickSearchSuggestion with the following content:
It looks like the Quick Search functionality works good:
So to execute GraphQL queries using Apollo GraphQL client, you can choose between two custom apollo react hooks:
The useLazyQery hook is perfect when you, for example, need to fetch data for GraphQL server on user action, user clicking, or typing.
Apollo React Hooks and cached data
Apollo client provides a cache mechanism called InMemoryCache. Thanks to that, the apollo cache query results in memory. Of course, Apollo react hooks supports that cache. You can set the default fetch policy globally and locally on each query.
Handling GraphQL errors
Lazy query error handling is pretty the same as when you use the useQuery hook. Please follow this article if you want to get more about GraphQL errors.
Did you like it? Share!
Each share supports and motivates me to create new content Thank you!
About the author
Frontend developer, Certified Magento Full Stack Developer, writer, based in Poland. He has eight years of professional Software engineering experience. Privately, husband and father. He likes reading books, drawing, and walking through mountains.