T
TanStack3y ago
national-gold

Programmatically set error on query with query client

Hey gang. I know it's possible to set query data using queryClient.setQueryData. Is it possible to set the error for a query? I can't seem to find the appropriate API to do that. As context: I've created a live query framework on top of React Query that fetches initial data while subscribing to updates via websockets. When websocket updates come in, the query cache is updated with queryClient.setQueryData. However, it's possible for websocket updates to return errors after the initial data is returned. I would love to be able to rely on React Query for handling these errors, but I don't know of a way to tell React Query that there is an error aside from throwing an error in the query function, which would be complicated to do in this circumstance.
6 Replies
graceful-blue
graceful-blue3y ago
interesting case - we indeed do not have an api for that, apart from:
queryClient.prefetchQuery({
queryKey: myKey,
queryFn: () => throw new Error("my error")
})
queryClient.prefetchQuery({
queryKey: myKey,
queryFn: () => throw new Error("my error")
})
a bit hack-ish and also async (no sync error setting) but maybe it helps your case?
national-gold
national-goldOP3y ago
I frickin' love it. Thanks @TkDodo 🔮 - that hack is just what I need! I'm just blown away by how simultaneously elegant and devilish that solution is 😈
graceful-blue
graceful-blue3y ago
hmm, this might have side-effects I haven't anticipated 😅 . For example, this queryFn is then stored and used for refetches 🤔
national-gold
national-goldOP3y ago
I'm not worried about that in my case. I've turned off refetches, and rely entirely on the websocket for updates.
graceful-blue
graceful-blue3y ago
just fyi, I found another solution:
const query = queryClient.getQueryCache.build(queryClient, options)

query.setQueryState({
...query.getQueryState,
error: new Error("my error")
})
const query = queryClient.getQueryCache.build(queryClient, options)

query.setQueryState({
...query.getQueryState,
error: new Error("my error")
})
that's pretty low level though, so you'd also need to set errorUpdateCount and errorUpdatedAt. If the prefetch works for you, stick with that 👍
national-gold
national-goldOP3y ago
You're amazing! 🙏

Did you find this page helpful?