Toast Not Displaying My Error From Db

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))
    }

}

If anyone knows anything about this would really appreciate it.

Does it work if you just throw a normal Error? Is ErrorResponse a custom error handler?

It throws the error Axios status 404 when it’s normal and ErrorResponse is a custom error handler.

class ErrorResponse extends Error {
    constructor(message, statusCode) {
        super(message);
        this.statusCode = statusCode;
    }
}

module.exports = ErrorResponse;

I am not sure why the server does not display the custom errors.

I noticed that I also can not print my data from my API request. I think if we fix that then it should display the error like on my heroku backend.

  const handleSubmit = async (e) => {
      e.preventDefault();
      try {
          const {data} = await axios.post(process.env.REACT_APP_LOGIN, {
            username, password
          });

          //no log of data
          console.log(`This is the data for the request ${data}`);

          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) {
        //404
        console.log(err.response.status);
        //object
        console.log(err.response.headers);
        //undefined
        console.log(err.response.message); 
        //undefined
        console.log(`This is the error: ${err.response.data.error}`);
        //undefined
        toast.error(`There is an error: ${err.response.data.error}`);
      }
    }

This is what I learnt as things to remember when showing a toast while debugging this issue : Make sure not to forget to call show() after the makeText. Check for the Context , if its the right one. The most important one , make sure your Android Notifications are on for your app, else the Toast will not be shown.
To display the Toast in center of the screen. If someone wants to adjust the position further, the third argument in setGravity takes in the yAxis offset in pixels. setGravity() should have returned Toast to be able to chain it.

This may help you,
Rachel Gomez

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.