I am using MongoDB and I installed react toastify to show errors from my backend for sign in but I can not seem to show them. How do I fix this issue? because I can output toast messages but not the errors.
//my frontend js file
const handleSubmit = async (e) => {
e.preventDefault();
try {
const {data} = await axios.post(process.env.REACT_APP_LOGIN, {
username, password
});
if (data.success === true) {
setValues({username: '', password: ''})
toast.success("Sign in successfully");
//save user in local storage
if (typeof window !== "undefined") {
localStorage.setItem("token", JSON.stringify(data));
}
navigate("/map");
}
} catch (err) {
console.log(`This is the error: ${err.response.data.error}`);
//this is supposed to display error not be undefined.
toast.error(`There is an error: ${err.response.data.error}`);
}
}
return (
<div className='loginContainer'>
<div className='logo'></div>
<AddLocationAltIcon/>
Pin
<form className='loginForm'>
<input type='text' className='usernameE' placeholder='username' onChange={handleChange('username')}/>
<input type='password' className='passwordE' placeholder='password' onChange={handleChange('password')} />
<button className='loginBtn' onClick={handleSubmit} type="submit">Login</button>
<button onClick={() => navigate('/register')} className="loginRegister">
Sign Up
</button>
</form>
</div>
)
//my backend js file
exports.signin = async (req, res, next)=> {
try {
const {username, password} = req.body;
//if no username and password
if (!username || !password) {
return next(new ErrorResponse(`Username and password are required`, 404))
}
//check username
const user = await User.findOne({username});
if (!user) {
return next(new ErrorResponse(`Invalid credentials`, 404))
}
//verify user password
const isMatched = await user.comparePassword(password);
if (!isMatched) {
return next(new ErrorResponse(`Cannot log in, check your credentials`, 404))
}
generateToken(user, 200, res);
} catch (error) {
console.log(error);
return next(new ErrorResponse(`Cannot log in, check your credentials`, 404))
}
}