I have an issue where on my signup page the response shows that the user already exists, however continues to the home page as if a new login was created. I want this to back back to the login page if the user exists. I have tried adding an if else block but that didn't work. I'm not sure what I am doing wrong.
const onSubmitForm = async (e: any) => {
e.preventDefault();
try {
const body = { email, password, name };
const response = await fetch('http://localhost:5000/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const parseRes = await response.json();
console.log(parseRes);
localStorage.setItem('token', parseRes);
// history.push('/home');
props.setAuth(true);
} catch (error) {
let errorMessage = 'Server error';
if (error instanceof Error) {
errorMessage = error.message;
}
console.error(errorMessage);
}
// eslint-disable-next-line no-lone-blocks
{
toggleSignup();
}
};
CodePudding user response:
If you want to conditionally go to a certain page based on the response from your server, you are correct in that a simple way to do it is with an if/else
statement.
Here's a simple example:
const onSubmitForm = async (e: any) => {
e.preventDefault();
try {
const body = { email, password, name };
const response = await fetch('http://localhost:5000/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const parseRes = await response.json();
// In YOUR code, you don't check the value of parseRes so your code goes straight to history.push('/home').
// You want to check the value of parseRes and conditionally go to a certain page based on the value
if (parseRes === 'User already registered') {
history.push('/login');
}
else {
localStorage.setItem('token', parseRes);
history.push('/home');
}
props.setAuth(true);
} catch (error) {
let errorMessage = 'Server error';
if (error instanceof Error) {
errorMessage = error.message;
}
console.error(errorMessage);
}
// eslint-disable-next-line no-lone-blocks
{
toggleSignup();
}
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Your current code does not check the value of parseRes
and will always execute history.push('/home')
since it's the next line down.
And just a side note, checking against the value 'User already registered' is not recommended, I just used that to give you an idea of what to do. Typically you'd want to check the HTTP response code (i.e 200, 400, 401, etc) or check some returned JSON value.