Reputation: 199
I'm trying to get data from database using mongodb and mongoose.
i have a request function:
componentDidMount(){
fetch('http://localhost:5000/tweet')
.then(function(response) {
return response.json();
})
.then(result=>{
this.setState({
tweetData:JSON.stringify(result)
});
console.log(this.state.tweetData);
});
}
I'm try show by console.log, it's ok:
but when i access the properties by property name the console.log show: null
why?
here is my backend code:
app.get('/tweet',(req,res)=>{
tweetData.find((err,data)=>{
if(err){
return res.json({success: false, error: err});
}
return res.json({success: true, data:data});
});
})
Upvotes: 0
Views: 119
Reputation: 112867
You are parsing the JSON and then stringifying it again. Remove JSON.stringify
and it should work as expected.
setState
is also asynchronous, so you can't access the new state in the statement below it. You can use the second argument of setState
which is a callback that will be called when the state has been set.
componentDidMount() {
fetch('http://localhost:5000/tweet')
.then(response => response.json())
.then(result => {
this.setState({
tweetData: result
}, () => console.log(this.state.tweetData));
})
}
Upvotes: 1
Reputation: 5912
You have to result.data
.
.then(result=>{
this.setState({
tweetData:result.data
},()=>{
console.log(this.state.tweetData);
);
});
And setState
is async you can use callback function to check state update
Upvotes: 1