Redirection Not Working Because Of Order Of Executions Of Functions
Solution 1:
This is happening because submitForm
and FormSubmitted
both contain asynchronous operations. This means that calling them one after another followed by RedirectionToPanel
does not guarantee that they execute in that order. Consider using the useEffect
hook to do the redirect once the token is set.
Also, the reason why the page is not redirecting is because you are not returning the Redirect component into the DOM tree. You can fix this by inserting it with a conditional statement that checks the submitted state
//when localStorage.getItem('token') changes, execute the callbackuseEffect(() => {
setSubmitted(true);
}, [localStorage.getItem('token')])
...
return (
...
<form style={{ width: '100%' }}
onSubmit={e => {e.preventDefault();
submitForm(LoginMutation);}}>
...
//This line can be anywhere in the return. Even at the end is fine
{submitted && <Redirectto='/panel'/>}
<Container />
);
If you want to do this without useEffect, you can use setSubmitted
within submitForm
. But even then, you must have {submitted && <Redirect to='/panel'/>}
somewhere in your DOM
functionsubmitForm(LoginMutation: any) {
const { email, password } = state;
if(email && password){
LoginMutation({
variables: {
email: email,
password: password,
},
}).then(({ data }: any) => {
localStorage.setItem('token', data.loginEmail.accessToken);
setSubmitted(true);
})
.catch(console.log)
}
}
return (
...
<form style={{ width: '100%' }}
onSubmit={e => {e.preventDefault();
submitForm(LoginMutation);}}>
...
//This line can be anywhere in the return. Even at the end is fine
{submitted && <Redirectto='/panel'/>}
<Container />
);
Solution 2:
As @wxker stated, you need to return <Redirect>
elements in the render method in order for the redirect to actually occur. E.g. https://codesandbox.io/s/proud-rgb-d0g8e.
Post a Comment for "Redirection Not Working Because Of Order Of Executions Of Functions"