Search code examples
reactjstypescriptreact-query

How to trigger API call only when manual search, or page are changed in React Query?


I have search form, and i only want to call the api when selectedPage or resultsPerPage change or when user click on search after write some things in the form.

With this, the api is called when the component is mounted:

  const [selectedPage, setSelectedPage] = useState<number>(1);
  const [resultsPerPage, setResultsPerPage] = useState<number>(2);

  const { data, isFetching, refetch } = useQuery<any[], Error>({
    queryKey: ['advancedSearch', selectedPage, resultsPerPage],
    queryFn: () => fetchAdvancedSearch(advancedFilter, selectedPage, resultsPerPage)
  });

  const handleSearch = () => {
    refetch();
  }

I tried with the disabled: true flag, witch works, but then it wont call the api when selectedPage or resultsPerPage change.


Solution

  • If you need your example to fetch data only when selectedPage or resultsPerPage has changed, you should use enabled option of the useQuery function. But instead of setting it to some constant value (e.g. true) you should make it depend from changes in selectedPage and resultsPerPage variables.

    You might introduce previousPage and previousResultsPerPage variables to track changes. I've updated your example accordingly:

    
    // Introduce custom hook usePrevious
    function usePrevious(value) {
      const ref = useRef();
      useEffect(() => {
        ref.current = value;
      });
      return ref.current;
    }
    
    ...
     
      const [selectedPage, setSelectedPage] = useState<number>(1);
      const [resultsPerPage, setResultsPerPage] = useState<number>(2);
    
      const previousSelectedPage = usePrevious(selectedPage);
      const previousResultsPerPage = usePrevious(resultsPerPage);
    
    
      const canFetch = selectedPage != previousSelectedPage || resultsPerPage != previousResultsPerPage;
    
      const { data, isFetching, refetch } = useQuery<any[], Error>({
      queryKey: ['advancedSearch', selectedPage, resultsPerPage],
        queryFn: () => fetchAdvancedSearch(advancedFilter, selectedPage, resultsPerPage),
        enabled: canFetch
      });
    
      const handleSearch = () => {
        refetch();
      }