0

I am trying to fetch all the articles from a document in MongoDB in React. It is perfectly working in Backend with NodeJS when I tested with Postman. But in Frontend , React, I am getting empty array. How to solve this.

Server.js (Backend)

app.get('/api/articles', async (req, res)=>{
    const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser:true, useUnifiedTopology:true})
    const db = client.db('my-blog')

    const articleInfo= await db.collection('articles').find({}).toArray(function(err, result){
        if (err) console.log(err)
        res.status(200).send(result)
        client.close()
    })
    
})

articlePage.js (FrontEnd)

componentDidMount(){
        const requestOptions = {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
        };
        const fetchdata = fetch('/api/articles/').then(res=>res.json())
        .then(data=>this.setState({articles:data}))
        console.log(this.state.articles)

    }

Api address is set up in package.json with proxy:http://localhost:8000

How to get the documents data from MongoDB in React?

1
  • Your console log is going to show the old state. State doesn't change until the next render. Commented Jun 13, 2020 at 6:37

2 Answers 2

1

Firstly, check if you the API call went through to the server from your React app. If it has, then check for the response code in the network. In your case, 200 is where you get the desired result from the API. If you are not getting the desired result, then check your collection and document names and also arguments your are passing in the query.

Sign up to request clarification or add additional context in comments.

Comments

0

As setState is not synchronized, you have to access it in the callback.

this.setState({ articles: data }, () => {
  console.log(this.state.articles)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.