I’m trying to route the user on login to a page depending on data I get from a useQuery call , but the onSuccess is too quick to run while the query hasn’t fetch yet , my code looks like this
const { data, refetch } = useQuery(["tracks"], getTracks, {
enabled: false,
});
const { mutate, isLoading, isError, error } = useMutation(login, {
onSuccess(d, v, c) {
Cookies.set("cookieToken", d?.access);
let type = Cookies.get("cookieToken");
type = parseJwt(type);
type = type.user_type;
refetch();
if (data) {
if (type === 5 || type === 6) {
navigate(`/${data?.object[0]?.id}?type=prio`);
} else {
navigate(`/${data?.object[0]?.id}?type=filtering`);
}
}
},
});
I want to onSuccess of the use mutation to fetch the query , wait for the result and navigate the user based on the data I get from the query , how to do so ?
I can’t run the useQuery before the onSuccess because it won’t succeed without having the token from the mutation
2
Answers
I think you need to
await
therefetch
, so something like this:Assuming you are using @tanstack/react-query v4+, maybe something like this might help?
Please refer to the "refetch" function signature and note that it returns a promise:
https://tanstack.com/query/v4/docs/react/reference/useQuery