I have a user profile which allows the user to update their information. I am trying to make user update their email, however the updated email is not saved to database.
EditProfile.js
//update user information on submit
const updateThisUser = (e) => {
e.preventDefault();
console.log(userEmail); //still shows the old input
Axios.post("http://localhost:8800/updateUser", {
_id: userId,
userEmail: userEmail,
}).then((res) => {
if(res.data.isUpdated){
let userId = res.data.id;
window.alert('Your profile has been updated!');
history.push(`/profile/${userId}`);
}
else{
window.alert('!')
}
})};
return(
<div>
<Form onSubmit = {updateThisUser}>
<h1 className="fs-1 d-flex justify-content-center text-center">Update My Profile</h1>
<Form.Group className="mb-3" controlId="userEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter your email here" defaultValue={userEmail}
onChange = {(event) => {
setUserEmail(event.target.value);
}}
/>
</Form.Group>
</Form>
</div>
)
POST request in index.js (server side)
app.post("/updateUser", function(req, res) {
const id = req.body._id;
let isUpdated = false;
try{
UserModel.findOne({_id:id}, function(err, user1){
if(user1) {
user1.userEmail = req.body.userEmail;
const updatedUser = user1.save();
res.send({
id: updatedUser._id,
isUpdated: true,
})
}
})
}
catch(err){
console.log(err);
}});
The weird thing is the window.alert('Your profile has been updated!');
does pop up after submitting the form, however it still does not save the new email to MongoDB.
I have also tried changing {defaultValue} to {value} for the text field input, however it won't let me type in the field.
Anyone knows the problem with my code? Any help appreciated. Thank you!