I’m building a search page with the following behavior:
- when the page is loaded, execute a query with default search params
- when the user updates the search params, execute a query with the new params
- when the user
clears
the search, clear any data but do not re-fetch the search until they have entered new params - when the user
resets
the search, execute a query with the default search params.
To handle case 3
, I am manually setting the data of the query, because I can’t find a method that will allow me to clear the data without re-fetching. This is causing a bug; if the user updates the search params, then clears the search, then uses the previous search params again, the query does not re-fetch, and the manually set "cleared" data persists.
What pattern/method should I be using to force the refetch, even if the query key already exists in the cache? I have tried using invalidateQueries
in my clear
call, but that causes the query to re-fetch, which is not the desired behavior.
const queryClient = useQueryClient();
const [params, setParams] = useState(defaultParams);
const {data, isLoading, isFetching} = useQuery({
querykey: ['search', params],
queryFn: () => fetch(...),
});
const clearSearch = () => {
queryClient.setQueriesData({queryKey: ['search'], exact: false}, []});
}
const resetSearch = () => setParams(defaultParams);
const submitSearch = (nextParams) => {
// if this is called with params = A, and then clearSearch is called,
// and this is called again with params = A, the query does not re-fetch
setParams(nextParams);
}
2
Answers
you should use the
useEffect
hook to refetch everytime the params changesYou can accomplish your result by using the the enabled property in useQuery Hook.
By checking if the param state is not a valid string, you can enable or disable on runtime the useQuery.
As example: