Problem:
Trying to get caching working with react-query. The code seems to be correct as I’m using both staleTime
and cacheTime
, but it keeps re-fetching data every after page reload. It’s not supposed to. It’s supposed to serve the cached data and stop fetching. There’s no console errors, either.
What I’ve Tried:
Using staleTime
and cacheTime
in order to cache, but it’s not caching.
Code:
Link to full code.
App.tsx:
import { useQuery } from "react-query";
import { fetchProducts } from "../src/services/api/Api";
function App() {
// Fetch the data
const { data, isLoading, error } = useQuery("products", fetchProducts, {
// Set stale/cache time
staleTime: 1000 * 60 * 5,
cacheTime: 1000 * 60 * 10,
refetchOnWindowFocus: true,
});
return (
<>
<ChakraProvider>
<Container maxW="1200px">
<Header data={data} isLoading={isLoading} error={error} />
<MainTable data={data} isLoading={isLoading} error={error} />
</Container>
</ChakraProvider>
</>
);
}
export default App;
API.tsx (API Fetch Function):
import axios from “axios”;
export const fetchProducts = async () => {
try {
const urlEn = "url-here";
const urlFr = "url-here-fr-CA";
// if URL contains /fr, load in FR API
// else, load in EN API
const urlParts = window.location.pathname.split("/");
const mainUrl = urlParts.includes("fr") ? urlFr : urlEn;
const response = await axios.get(mainUrl);
const products = response.data.groups;
console.log("Fetched data in API component:", products);
return products;
} catch (error) {
console.error("Error:", error);
throw error;
}
};