Vikrant Agrahari
Vikrant Agrahari

Reputation: 163

Why am I getting empty array in fetch request to MongoDB from ReactJS?

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?

Upvotes: 0

Views: 418

Answers (2)

Eason
Eason

Reputation: 518

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

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

Upvotes: 0

Kishan Suvarna
Kishan Suvarna

Reputation: 11

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.

Upvotes: 1

Related Questions