T
TanStack2y ago
wise-white

Navigate is too fast...

So I have a login page which calls a login endpoint on the server using useMutation. My server returns a cookie and I can see it in my browser storage. After I call mutation.mutate() I navigate to my dashboard page, which has a beforeLoad that checks for the cookie. I think I'm redirecting too fast and the cookie hasnt been saved by the browser. I added a 500ms sleep which seems to fix the issue but I'm wondering if there are more elegant methods to ensure that the browser has saved the cookie before I redirect. this is my related code
const mutation = useMutation({
mutationFn: async () => {
try {
const r = await axios
.postForm<LoginType>("http://localhost:8000/login", {
username: name,
password: "100"
}, {
withCredentials: true,
})
return r.data
} catch (err) {
console.log(err)
}
},
onSuccess: async () => {
await sleep(500)
navigate({ to: "/" })
}
})

const handleLogin = async (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault()
setIsSubmitting(true)
mutation.mutate()
}
const mutation = useMutation({
mutationFn: async () => {
try {
const r = await axios
.postForm<LoginType>("http://localhost:8000/login", {
username: name,
password: "100"
}, {
withCredentials: true,
})
return r.data
} catch (err) {
console.log(err)
}
},
onSuccess: async () => {
await sleep(500)
navigate({ to: "/" })
}
})

const handleLogin = async (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault()
setIsSubmitting(true)
mutation.mutate()
}
3 Replies
rising-crimson
rising-crimson2y ago
Alot of this is dependent on how your specific auth system works. A network request is only considered to be done after everything has been completed (ie. Request sent, Response received, and Cookies Set). You could possibly return the full request from the mutationFn, and check its values in the onSuccess callback before calling navigate. Does your auth state get persisted to React Context or some state management system? How do you pull user_id or client_id values?
wise-white
wise-whiteOP2y ago
Well I'm using the react-cookie plugin [https://www.npmjs.com/package/react-cookie] and I use the useCookie hook and pass it as part of the route context. I'm wondering if the cookies aren't refreshed by the plugin right away in which case my navigation might be too quick? I tried using the onSuccess callback as well but that didnt help which leads me to believe that the newtwork request did work but I might have to manually force a cookie refresh before navigating?
national-gold
national-gold2y ago
Regarding how your authentication is setup client side, I assume ur probably using react query to call API routes that check for cookies to know if a user is authenticated before returning data That case you need to invalidate those queries prior to navigating on mutation success

Did you find this page helpful?