Mutations depending on result of other queries #3212
-
Hello there, In the app I'm working, we manage the authentication token via React-Query, and consume this query in other queries hooks so that we take advantage of the stale management provided by RQ, as we need to refresh the token periodically. The custom hook for getting the token looks something like this: export const useToken = () => {
return useQuery(
['token'],
() => loginUser({ ... }),
{
select: (data) => data.token,
staleTime: 1000 * 60 * 60, // the token is only valid for 1 hour
}
);
}; An "authenticated" query would look like this: export const useData = () => {
const tokenQuery = useToken();
return useQuery(
['data'],
() => fetchData({ token: tokenQuery.data }),
{
enabled: tokenQuery.isSuccess
}
);
}; so we make this query dependent of the previous one, which stores a valid token in the cache, this way we are sure that before the While working with mutations, we don't have the Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hm. I would argue that While your dependent query might work, there is no guarantee that you get a new token after one hour. For example, if you have a successful token and the hour passes, the token query becomes stale. If you then mount Usually, a better approach is to:
Personally, I think cookies are a better way to manage access tokens, because they are sent automatically. If they are secure, httpOnly and same-site, I don't see a reason not to use them. But its a different architecture (and you need to have browsers that support same-site cookies, otherwise you have to manage CSRF and that sucks) |
Beta Was this translation helpful? Give feedback.
Hm. I would argue that
loginUser
itself should be a mutation: https://twitter.com/TkDodo/status/1483157923572457476While your dependent query might work, there is no guarantee that you get a new token after one hour. For example, if you have a successful token and the hour passes, the token query becomes stale. If you then mount
useData
,useToken
will trigger a background refetch, but it will stay in success state and yourdata
query will be immediately enabled, running with the outdated token.Usually, a better approach is to: