I have built a simple application with react and redux for user registration and verifying email.
I have two components Register.js and VerifyEmail.js.
In Register.js, i collect the user input and send it to the server using actions defined in redux. If the signup was successful a redux state signupSuccess is set to true. In Register.js i will check if signupSuccess is true i will redirect the user to VerifyEmail.js component otherwise i will display the errors.
But the problem is if user clicks the back button and wishes to re-enter the sign up information, as the signupSuccess state is still true, it again redirects the user to VerifyEmail.js. But i don't want to redirect the user when he came by pressing back button from VerifyEmail.js.
I have posted only some parts of code to simplify the description.
Register.js
function Register(props) {
let history = useHistory();
// props from redux store
const { loading, signupErrors, signupSuccess, sendUserSignupData } = props;
const [formData, SetFormData] = useState({
email: '',
username: '',
password: '',
password2: '',
})
// signupSuccess is a redux store state is true (which is set to true after a asynchronous task of sending user data to server side and validation )
if (signupSuccess) {
history.push('/verify-email');
}
const handleSubmit = (e) => {
e.preventDefault();
sendUserSignupData(formData); // redux async function - this function sets signupSuccess to true
};
return (
// sign up form
)
}
Some possible solutions that i could think of is
- If there was any way to read the previous path from history stack in Register.js i could check if the previous path is '/verify-email' and not to redirect in this case. I referred this post on how to read the previous path in history stack Detect previous path in react router? But the solution won't apply in my case as the user is going to Register.js by pressing back button from VerufyEmail.js (it could have worked if i was redirecting him by using history.push or something).
- I can set up an additional redux state redirectonlyOnce set it to true for first time and refer it in next if checks. But it is not a good solution as those states persist after page refreshes and user won't be redirected to VerifyEmail.js if he goes back to Register.js refreshes the page and then submits the form.
Any help will be highly appreciated. Thank you.