Reset a react-query useQuery hook to clear data on the rendered page

I am writing a search component which uses react query to fetch the data.

export default function useSearchResults({
    query,
}: IUseGetSearchResultsProps): QueryObserverResult<IResponse<ISearchResult>> {
    return useQuery(
        [SEARCH_RESULT_QUERY_KEY, { query }],
        (): Promise<IResponse<ISearchResult>> => getSearchResults({ query }),
        {
            enabled: false,
            keepPreviousData: true,
        }
    );
}

Which I then import in my component, and refetch the data when the user enters a search term:

  const [searchTerm, setSearchTerm] = React.useState<string>("");
  const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    e.preventDefault();
    setSearchTerm(e.target.value);
  };

  const { data, refetch } = useSearchResults({ query: searchTerm });

  React.useEffect(() => {
    if (searchTerm.length > 0) {
      refetch();
    }
  }, [searchTerm]);

There is a requirement to not show any data when there is nothing in the searchTerm i.e. searchTerm is an empty string.

However, the API returns all results when a search term is not passed to it and I cannot alter that behaviour.

Is there a way to reset useQuery hook to return data as an empty array?

Source: Ask Javascript Questions

LEAVE A COMMENT