data always returns the last api response
Hello everyone! data always returns the last api response. Is it possible to get only fresh response from data. In case of api failure or ongoing request, data return null ?
const {refetch, isFetching, data, error, isSuccess} = useQuery({
queryKey: ['todos'],
queryFn: query,
staleTime: 0,
enabled: true,
});
5 Replies
continuing-cyan•9mo ago
You aren't really showing or asking much here. The pseudo code has a static
queryKey
, as in 'todo'
with no variables, so I'd never expect this to refetch for youcontinuing-cyan•9mo ago
This might be worth the read: https://tkdodo.eu/blog/effective-react-query-keys
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
extended-salmon•9mo ago
one principal is that we never delete data just because a refetch failed. very often, continuing to show the stale data is better. However, you can get that behaviour by just doing a simple check like:
this will give you
null
for data
even in error cases, when stale data might still be cached.extended-salmonOP•9mo ago
Thanks @TkDodo 🔮 . Is it possible to use a single custom hook for handling get, put and post requests, or do i need to create multiple hooks for each request? I'd very much like to limit it to 2-3 hooks(1 for each get, post and put). Also how should we handle error codes from api's? Is there a way to create a global handler that would handle all the responses and return data or error accodingly, or should i use Interceptors for that?. Btw thank you for your detailed blog on Tanstack!
national-gold•9mo ago
Assuming your using the http verbs as intended, my recommendation is to do GET's in queries and POST, PUT and DELETE in mutations
And Query isn't coupled with http at all; it just handles promises.