0

I have the following below 2 functions attempting to get data out of a mongo database from an express server endpoint I have set up. This code is in my React front-end app.

export function getContacts() {
  let data = fetch('/api/contacts').then((data) => {
    return data.json();
  }).catch(err => console.log(err));

  return data;
}

and the following that calls it

const initialState = getContacts()
  .then((body) => {
    console.log('body: ');
    console.log(body);
    return body;
  }).catch(err => console.log(err));

when I log body it is a promise. I was expecting a json array of documents from the db. My getContacts() is supposed to return a promise and then my callback in initialState gets the data from it.

intA
  • 2,513
  • 12
  • 41
  • 66
  • you get a `Promise` because `fetch` returns a `Promise` - though, body should never be a Promise - that is odd, are you sure you've written the code as you are really using it? `initialState` will be a promise - but `body` where you console.log it wont – Jaromanda X Apr 04 '19 at 03:47
  • 1
    @intA, as you mentioned in this [post](https://stackoverflow.com/questions/55527466/how-can-i-use-async-await-while-assigning-a-variable?noredirect=1#comment97759038_55527466) under the comment section. It seems there is no answer with this because your backend server is faulty. Kindly delete this question to not pollute SO. Thank you! – jtabuloc Apr 05 '19 at 03:07

1 Answers1

0

The data.json() call is actually returning a promise by design. Take a look at the documentation page here for an explanation as to why.

You can fix it by chaining another then call or by declaring your function as async and using await.

John
  • 1,530
  • 1
  • 10
  • 19
  • OP is calling another .then ... `getContacts().then((body)` and claims `body` is a Promise ... which it wont be – Jaromanda X Apr 04 '19 at 04:11
  • @JaromandaX I don't think that is the case. The OP is returning `data` (Fetch) from `getContacts()`. At that point, it should get the original promise passed in when the chained `then` is resolved. So `body` should be an instance of the `Response interface`. Unless I am missing something? – John Apr 04 '19 at 04:40
  • yes, the piece of code I quoted - clearly you don't understand how promises chain – Jaromanda X Apr 04 '19 at 04:46
  • @JaromandaX hmm, ok. Seems like `body` is undefined when I log it. But why is that value not getting stored in `initialState`? – intA Apr 04 '19 at 23:53
  • You said it was a promise. Now it's undefined. Is this browser code? If so check the developer tools console and network tabs to see what's going on – Jaromanda X Apr 04 '19 at 23:59