dinosaur
dinosaur

Reputation: 199

Why I can't access the properties json data by the property name in reactjs?

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:

enter image description here 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

Answers (2)

Tholle
Tholle

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

Amruth
Amruth

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

Related Questions