How do I make useMutation call with time interval?
I need to refetch token every 60hours or when token expires, currently I am using a useEffect in AuthProvider but it doesn't seem to work if people keep it open and don't change tabs/navigation, so I wonder if I can use useMutation instead? but I don't see any time interval params for this... it seems the time interval is only available for useQuery. What is the best way to do that?
4 Replies
dependent-tan•3y ago
An interval of 60 hours would only work if the user leaves the browser/tab open for 60 hours, which is highly unlikely. When the page is refreshed the interval would restart, so this is probably outside the scope of tanstack query.
A common thing to do for token renewal is to renew when it has expired and you're getting a 401 response back. Something like "call an api using the token -> token has expired so api responds with error (probably 401) -> renew token (probably using a refresh token) and call the api again". This is not my area of expertise though, so I'd recommend more research on the matter.
other-emeraldOP•3y ago
Thanks! Yes currently I am using the expiration date to set refetch, I will see whether it works properly.
Ok. Now I have this strategy:
- useEffect -> runs depending on location (path) change, that means if the user changes the path, I will run this once, check if token expires, if not don't do anything, if yes, refetch access token;
However, in case the user never switch path, they just stay on the same page all the time, then I run the check every 60hrs (depending on the token expiration time), if the location is still the same, then run function to check: if token expires, refetch access token, otherwise don't do anything. Well they both use the same function, of course.
Otherwise I think I'd have to write that refetch token function in every useMutation or useQuery's onError block...
I am not sure those are the best strategy though.. but for now it seems to solve my problem....
dependent-tan•3y ago
When creating the
QueryClient, you can set some default options for queries and mutations. So you can set a global onError that'll apply to every mutation or queries:
Or you can create your own custom hook that wraps useMutation and passes the options you need.other-emeraldOP•3y ago
Oh that's very handy... but it might be confusing as sometimes 401 doesn't mean token expires, (as in our case), it can also mean sth else...
I will mark it solved for now