#Race condition with beforeLoad and routerContext

7 messages · Page 1 of 1 (latest)

timber drift
#

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?

#

Think this may be answered in the Routing with async data post below, will give the useEffect trick a shot

timber drift
#

yea thats a bit different, the login function on mine should be synchronous and thus finish + update context before calling navigate but navigate fires before the context resets

#

this is probably some basic React problem 🤔

#

yep, simple react problem with context and state.

  const { login, error, token } = useAuth()
  const [errorMessage, setErrorMessage] = useState('')
  const navigate = useNavigate()

  useEffect(() => {
    if (token) {
      navigate({ to: '/user' })
    }
  }, [token, navigate])

  const form = useForm({
    ...formOpts,
    onSubmit: async ({ value }) => {
      mutation.mutate({ ...value })
    },
  })

  // TODO: Account for API errors
  const mutation = useMutation({
    mutationFn: (signUpFormData) => {
      return signUp(signUpFormData)
    },
    onSuccess: (data) => {
      if (data.access_token) {
        login(data.access_token)
      }
    },
    onError: (error) => {
      console.error('Sign up failed: ', error.message)
      // TODO: Show an error message to the user here
      setErrorMessage(error.message)
    },
  })
timber drift
#

onSettled also works here in the mutation

willow vigil
#

I had the same issue maybe I would try a useEffect