skip to Main Content

I’m building a search page with the following behavior:

  1. when the page is loaded, execute a query with default search params
  2. when the user updates the search params, execute a query with the new params
  3. when the user clears the search, clear any data but do not re-fetch the search until they have entered new params
  4. 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


  1. you should use the useEffect hook to refetch everytime the params changes

    useEffect(() => {
    // refetch
    }, [params])
    
    Login or Signup to reply.
  2. You 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:

    export default function Dummy() {
      const [params, setParams] = React.useState('');
      useQuery({
         queryKey: ['search', params],
         enabled: Boolean(params),
         queryFn: () => console.log(params, 'print'),
      });
    
       return (
         <div className={styles.container}>
           <input
             type="text"
             value={params}
             onChange={(e) => setParams(e.target.value)}
           />
        </div>
      );
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search