TanStackT
TanStack2y ago
7 replies
ill-bronze

Race condition with beforeLoad and routerContext

I have a function that does the following in a mutation:


const mutation = useMutation({
  mutationFn: (signUpFormData) => {
    return signUp(signUpFormData)
  },
  onSuccess: (data) => {
    if (data.access_token) {
      login(data.access_token)
      setTimeout(() => {
        navigate({ to: '/user' })
      }, 1000)
    }
  },
  onError: (error) => {
    console.error('Sign up failed: ', error.message)
    // TODO: Show an error message to the user here
    setErrorMessage(error.message)
  },
})


If I remove the setTimeout, I get a null value for token in my beforeLoad of /user.

export const Route = createFileRoute('/user/')({
  beforeLoad: ({ context, location }) => {
    const token = context.auth.token

    if (!token) {
      throw redirect({
        to: '/sign-in',
        search: {
          redirect: location.href,
        },
      })
    }
  },
  component: () => <User />,
})


How can I avoid this race condition?
Was this page helpful?