Tomasz Foryś
Tomasz Foryś

Reputation: 1

I receive empty object after fetching to react from server

I send data from server using this code:

app.get('/emails', function(req, res) {
var tablica_zadan = [];
   db.collection('emails').find({}).toArray(function(err,docs){
      docs.forEach(function(doc) {
        /*console.log('wypisz numery zadan' + doc.tresc);*/

        tablica_zadan.push(doc);

      });
      /*console.log(tablica_zadan);*/
      res.send(tablica_zadan);
    });

  });

})

In my react file I fetch it using code:

var docs = fetch('http://localhost:3000/emails')
    .then(function(response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }

        return response.json();
    })
    .then(function(error) {
        console.log(error);
    });

console.log(docs instanceof Array);
console.log(docs);

and when I want to print docs by console.log(docs) it seems to be empty... I have message:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

I don't know how improve it. Please help me.

Upvotes: 0

Views: 51

Answers (1)

Icid
Icid

Reputation: 1464

docs will be a Promise.

To get the actual value, you will need to do the following...

docs.then(function(value) {
  console.log(value instanceof Array);
  console.log(value);
});

Upvotes: 2

Related Questions