Next.js Discord

Discord Forum

Server Functions Redirects from a Client Component

Answered
Thai posted this in #help-forum
Open in Discord
ThaiOP
I am having issues with a login component where I call a server function, the login is super simple like this (summary of the code:

'use client'
function LoginComponent() {
   const [state, formAction] = useFormState(LoginAction, { errors: '' })

  return <>
    <form action={formAction}>
      <!-- form here --->
    </form>
  </>

}


'use server'

export async function LoginAction(prevValue: any, formData: FormData) {

  const authResult = await GetAuth(formData);

  if (authResult.requireMFA){
    redirect('/auth/verify/')
  }

  if (authResult.success){
    redirect('/')
  } 

}


This is not working for me and I have seen a number of issues reported on github related to redirect , I am out of ideas but something this simple gives me so much pause about next.
Answered by Thai
yeah it is valid, I had to do a work around in the client side of doing this essentially:
    const [state, formAction] = useFormState(VerifyAction, { errors: '' })
    const router = useRouter();
    useEffect(() => {

        if (state.success) {
            router.push(`/`);
        }

        if (state.mfaSent) {
            router.push(state.mfaUrl);
        }
    }, [state])
View full answer

5 Replies

What exactly isn't working, also are you checking to make sure both prevValue and formData are what you expect?
ThaiOP
yeah it is valid, I had to do a work around in the client side of doing this essentially:
    const [state, formAction] = useFormState(VerifyAction, { errors: '' })
    const router = useRouter();
    useEffect(() => {

        if (state.success) {
            router.push(`/`);
        }

        if (state.mfaSent) {
            router.push(state.mfaUrl);
        }
    }, [state])
Answer
I don't get it, so you solved the issue or not?
ThaiOP
I just did it just now
Ok