I’m new to React and I’m trying to make a route to keep the user logged in after registering, so that I can use their user details to populate fields in the homepage. I first tried doing this the way I used to before I started learning react, by saving the data in res.locals, but this doesn’t seem to work in react. Now I’m trying to do it with local storage. First, I send a post request when the user submits a form:
onSubmit(e) {
e.preventDefault();
const newUser = {
userName: this.state.userName,
userEmail: this.state.userEmail,
userPassword: this.state.userPassword,
}
console.log(newUser);
axios.post('http://localhost:5000/user/signup', newUser)
.then(res => localStorage.setItem("CurrentTeacher", (res.data));
console.log(localStorage.getItem("CurrentUser"));
}
The post request works fine and the user is added to my DB with no issues, but localStorage.getitem line always returns undefined. Below is my post request in my userRoute.js file (I’m using Passport to register my user):
router.route('/signup').post(async (req, res) => {
const username = req.body.userName;
const userEmail = req.body.userEmail;
const password = req.body.userPassword;
try{
const newUser = new User({userEmail,username});
const registeredUser = await User.register(newUser,password);
req.login(registeredUser,err=>{
if(err) console.log(err);
console.log("NEW USER: " + req.user)
})
} catch(e){
console.log(e.message)
}
});
I’ve tried several different things, like adding JSON.stringify to my res.data. Infact, it doesn’t even look like my .then code is firing because when I run a simple console.log with .then, I get nothing.