I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :
SubmitClick(){
if (this.state.password !== this.state.reTypepassword){
alert('Passwords do not match. Please check your data !');
} else {
//console.log(this.state); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Accept': 'application/json',
//'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
first_name: this.state.first_name,
last_name: this.state.last_name,
personal_phone: this.state.personal_phone,
password: this.state.password
})
})
.then(response => response.json())
.then(parsedJSON => console.log(parsedJSON._id))
.catch(error => alert('Check your data', error))
.then(this.props.history.push('/get')) // change page layout and URL
}
console.log(this.state.id); //debug to see if the _id is saved in my state
}
Here is my constructor:
constructor(props){
super(props);
this.state={
email:'',
first_name:'',
last_name:'',
personal_phone:'',
password:'',
reTypepassword:'',
id:''
}
}
I tried calling a function after parsedJSON
that used this.setState()
, using function(parsedJSON){this.state.id : parsedJSON._id}
. I tried with a new function like this:
changeID(parsedJSON){
this.setState({id : parsedJSON._id})
}
and changing the .then(parsedJSON => console.log(parsedJSON._id))
to .then(parsedJSON => this.cahngeID(parsedJSON))
. But none of then worked...
I left the code with .then(parsedJSON => console.log(parsedJSON._id))
so can make sure that I can see this value, and in my console it`s printed perfectly.
Here is a example of the response send by my backend: {"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}
How can I get the "_id" from my response?