T
TanStack11mo ago
rare-sapphire

Any thoughts on why I'd see a tanstack query go "stale" in the dev tools but not get re-queried?

I have two components, one which allocates a "create-new <thing>" button. The other component queries the backend for the things and renders them out as cards. When the user creates a new thing, clicks the button I invalidate the query to force a re-fresh of cards. In the dev tools I see the queries go stale, but it never re-freshes. Maybe this should be a mutation instead? (update list, then re-render the list?)
3 Replies
stormy-gold
stormy-gold11mo ago
That just means data is stale it doesn't necessarily mean it's going to be refetched. Sounds like you want something like:
// Some list component
const { data: cards } = useQuery({
queryKey: ['cards'],
queryFn: ...
})
// Some list component
const { data: cards } = useQuery({
queryKey: ['cards'],
queryFn: ...
})
// Some create component
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: ...,
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['cards']
})
}
})

return (
<button onClick={() => {
mutate(...)
}}>Create</button>
)
// Some create component
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: ...,
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['cards']
})
}
})

return (
<button onClick={() => {
mutate(...)
}}>Create</button>
)
rare-sapphire
rare-sapphireOP11mo ago
I actually realized my issue - I wasn't awaiting the API call to create before calling invalidate. The code sample you provided was exactly what I have ❤️ Just missng the await.. so it was invalidating before the DB actually updated lol
stormy-gold
stormy-gold11mo ago
Sounds like this rule could be your friend: https://typescript-eslint.io/rules/no-floating-promises/
no-floating-promises | typescript-eslint
Require Promise-like statements to be handled appropriately.

Did you find this page helpful?