'How do I get my app to redirect a user to a page after they have registered?

Perhaps I am placing the second router.replace('/contact'); line in the wrong position? Though that doesn't make sense given the redirect works well when a user logs in. Any assistance is greatly appreciated.

    if (isLogin) {
  const result = await signIn('credentials', {
    redirect: false,
    email: enteredEmail,
    password: enteredPassword,
  });

  if (!result.error) {
    // set some auth state
    router.replace('/contact');
  }
} else {
  try {
    const result = await createUser(enteredEmail, enteredPassword);
    console.log("hi");
    console.log(result);
    router.replace('/contact');
  } catch (error) {
    console.log(error);
  }
}

}



Solution 1:[1]

I don't know much about Next. In case of using only React, assuming there is a Button to check the credentials, I would use Link of 'react-router-dom' to wrap the Button like this:

<Link to={`/${redirect}`}>
    <Button onClick={handleSubmit(email, password)}>
        Submit
    </Button>
</Link>

Declare state of redirect:

const [redirect, setRedirect] = React.useState('contact');

Declare function handleSubmit:

const handleSubmit = (enteredEmail, enteredPassword) => {
    const result = await signIn('credentials', {
        redirect: false,
        email: enteredEmail,
        password: enteredPassword,
    });
    if (!result.error) {
        setRedirect('contact');
    }
    else setRedirect('user');
}

Solution 2:[2]

This is how I do it in React:

import { useHistory } from "react-router-dom";

const Example = () => {
    let history = useHistory();

    //inside function:
   try {
     const result = await createUser(enteredEmail, enteredPassword);
     history.push('/'); //route you want here, 
   } 
   ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thitbachi
Solution 2 ssunsset