How to keep previous successfully fetched data when using useQuery

47 views Asked by At

I'm currently working on implementing a GET request using useQuery from the react-query library. Here's the relevant code snippet:

import queryString from "query-string";
import { useRouter } from "next/router";
  
const { query } = useRouter();

const { data: statsData, isLoading: statsLoading } = useQuery(
    ["stats", queryString.stringify(query)],
    ({ queryKey }) =>
      axios.get(`/statistics?${queryKey[1]}`).then(({ data }) => data),
    {
      onError: () => showErrMessage("500"),
    }
);

The issue I'm encountering is that whenever the request fails, it resets the previously fetched data. Here's how I'm attempting to display the data:

{statsData?.total_sales}

How can I ensure that the data remains displayed even if the request encounters an error, rather than resetting to empty?

0

There are 0 answers