-
I have read react-query documentation regarding query invalidation. However, it doesn't seem to work for me. Here is the code: import React from "react";
import ax from "axios";
import { useQueryClient, useQuery } from "react-query";
export default function App() {
const queryClient = useQueryClient();
const [poke, setPoke] = React.useState("pikachu");
const getPokemon = async (id) => {
try {
const pokemon = await ax.get("https://pokeapi.co/api/v2/pokemon/" + id);
return pokemon;
} catch (err) {
throw new Error(err.message || "error.unknown");
}
};
const { data, isLoading, isError } = useQuery(
["get-pokemon", poke],
() => getPokemon(poke),
{ cacheTime: 100000000 }
);
const invalidate = () => queryClient.invalidateQueries("get-pokemon");
return (
<>
{isLoading && "loading"}
{isError && "error"}
{data && data.data.id}
<button onClick={() => setPoke("pikachu")}>search pikachu</button>
<button onClick={() => setPoke("ditto")}>search ditto</button>
<button onClick={() => invalidate()}>invalidate</button>
</>
);
} So the function invalidate() should invalidate the query "get-pokemon". I should see a loading state when pressing the "get pikachu" button again. But it behaves like the cache is still valid. How to fix this? Here is also a sandbox: https://codesandbox.io/s/cache-invalidation-lbj76?file=/src/App.js:0-1006 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Invalidating a query marks the query as stale and React Query will automatically re-fetch that query as a result. So even if you invalidate a query hard loading will not occur because any subsequent query of the same instance is happening in the backgound for great UX. If you want to show loading state whenever data is being fetched you'll need to use |
Beta Was this translation helpful? Give feedback.
-
I think this is the same as this stackoverflow question, which has been answered: https://stackoverflow.com/questions/66796136/how-to-invalidate-cache-with-react-query-v3 |
Beta Was this translation helpful? Give feedback.
Invalidating a query marks the query as stale and React Query will automatically re-fetch that query as a result. So even if you invalidate a query hard loading will not occur because any subsequent query of the same instance is happening in the backgound for great UX. If you want to show loading state whenever data is being fetched you'll need to use
isFetching
instead ofisLoading
. I hope this helps!