When using the React Query library for data fetching, sometimes we may not want to fetch data immediately after the component renders. For example, we might want to start fetching data only after the user completes certain actions, such as filling out a form or clicking a button. React Query provides several ways to implement delayed fetch calls.
1. Using the enabled option
The useQuery hook and its variants allow us to control when the query executes via the enabled option. enabled accepts a boolean value; when set to false, the query does not execute automatically.
Example code:
javascriptimport { useQuery } from 'react-query'; function fetchData() { return fetch('/api/data').then(res => res.json()); } function MyComponent({ shouldFetch }) { const { data, error, isLoading } = useQuery('data', fetchData, { enabled: shouldFetch, // Control whether to execute fetch }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error occurred!</div>; return <div>{data}</div>; }
In this example, shouldFetch is a boolean value that triggers the fetchData function when set to true. We can set this value based on user interactions, such as after specific actions.
2. Using the useLazyQuery variant of useQuery
useLazyQuery is similar to useQuery, but it does not trigger the query immediately when the component renders. Instead, it provides a trigger function that we can call at the appropriate time.
Example code:
javascriptimport { useLazyQuery } from 'react-query'; function fetchData() { return fetch('/api/data').then(res => res.json()); } function MyComponent() { const [fetchData, { data, error, isLoading }] = useLazyQuery('data', fetchData); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error occurred!</div>; return ( <div> <button onClick={() => fetchData()}>Fetch Data</button> {data && <div>{data}</div>} </div> ); }
Here, the fetchData function is the trigger provided by useLazyQuery, which we bind to a button's click event. This way, data fetching only occurs after the user clicks the button.
By using these methods, we can flexibly control React Query's fetch calls to better adapt to complex user interactions and data dependencies.