Summary:
I am trying to display a message from controller (backend) in notification (toast) using (react-toastify). And then whenever i try to login (cliking the login button) with a wrong e-mail, a toast appears with a message that we can find in the controller file (exemple: 'User with email does not exist' or 'Please enter all fields') ...etc, the message may vary depending on the status
or message
ofcourse.
- My code (Back):
back/controllers/user.js:
login: (req, res) => {
const { email, password } = req.body
if (!email || !password)
return res.status(400).json({ message: 'Please enter all fields' }) <=== this is the message i want to display in toast.
User.findOne({ email }, async (err, user) => {
if (!user) {
res.status(403).json({ message: 'User with email does not exist' }) <=== this is the message i want to display in toast.
console.log('wrongmail');
} else {
const ismatch = await bcrypt.compare(password, user.password)
if (ismatch) {
console.log('ismatch');
const token = signToken(user._id, user.role);
res.cookie("access_token", token, { maxAge: 3600 * 1000, httpOnly: true, sameSite: true });
return res.status(200).json({ isAuthenticated: true, role: user.role })
} else {
res.status(403).json({ message: 'Invalid password !' }) <=== this is the message i want to display in toast.
}
}
})
},
- My code (Front):
Front/src/views/Login/index.jsx:
import React, { useState } from 'react'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export default () => {
const notify = () => toast(""); <=== What should i put here to be rendred?
return (
<div className="col-lg-6">
<fieldset>
<input value={email} onChange={(e) => setemail(e.target.value)} type="text" name="email" id="email" pattern="[^ @]*@[^ @]*" placeholder="Your Email" required />
</fieldset>
<fieldset>
<input value={password} onChange={(e) => setpassword(e.target.value)} type="password" name="password" id="subject" placeholder="password" autoComplete="on" />
</fieldset>
<fieldset>
<button type="submit" id="form-submit" className="main-button" onClick={notify}>Login</button>
<ToastContainer />
</fieldset>
</div>
)
}
I added the gist code in my Login/index.jsx that i found it here: https://fkhadra.github.io/react-toastify/installation, but i can't manage to find a way to call any of messages from controller file (BE) to render as i explained at first in summary.