T
TanStack2y ago
exotic-emerald

InvalidateQuery does not trigger refetch.

This must be a really noob issue but for some reason I have trouble triggering refetch with invalidateQuery(). I have a grid and a details panel and I would like to reload the details panel when user clicks on a row. User could also edit the info so therefore I'd prefer useQuery instead of just useEffect for this page. But the panel doesn't change until I force the entire view to refetch with window focus refetching. All I have is
queryClient.invalidateQueries({
queryKey: ["itemversions"],
refetchType: "all"
});
queryClient.invalidateQueries({
queryKey: ["itemversions"],
refetchType: "all"
});
in the row click event and
const { isLoading, error, data } = useQuery({
queryKey: ['itemversions'],
queryFn: () => getItemVersion(itemId, version),
})
const { isLoading, error, data } = useQuery({
queryKey: ['itemversions'],
queryFn: () => getItemVersion(itemId, version),
})
in the details pane. itemId is a prop and it is correctly set. So what am I missing?
7 Replies
graceful-blue
graceful-blue2y ago
where is the queryClient coming from ?
exotic-emerald
exotic-emeraldOP2y ago
from useQueryClient()
graceful-blue
graceful-blue2y ago
then it should work
exotic-emerald
exotic-emeraldOP2y ago
Yeah, well.. so I thought as well. This is how I set it up:
export default function Home() {
const queryClient = new QueryClient();

return (
<QueryClientProvider client={queryClient}>
<main>
<MainWindow />
</main>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
export default function Home() {
const queryClient = new QueryClient();

return (
<QueryClientProvider client={queryClient}>
<main>
<MainWindow />
</main>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
Components that need this are inside MainWindow. I can see from devtools that the query is stale but it never seems to be refetched.
flat-fuchsia
flat-fuchsia2y ago
if you are creating your QueryClient inside a component, you need to make sure it is stable to prevent its state being lost on a rerender. Try this.
const [queryClient] = useState(() => new QueryClient());
...
const [queryClient] = useState(() => new QueryClient());
...
graceful-blue
graceful-blue2y ago
React Query FAQs
Answering the most frequently asked React Query questions
exotic-emerald
exotic-emeraldOP2y ago
Hadn't seen that but it still wouldn't work. I then realised that I can actually just use useEffect in this case as it gets the two parameters that I need to correctly refresh the view.

Did you find this page helpful?