0

I have this React project, in which I fetch data from a firebase database and construct a object called "statehelp" from the results. Now for some reason, if I console log the whole statehelp Object I get all its contents, however if I want to access statehelp.contents or statehelp.products they are undefined.

componentDidMount() {
  var statehelp = {
    content: {},
    products: {}
  }

  getFarm(this.id).then(result => statehelp.content = result)
  getProduct(this.id).then(result => statehelp.products = result)
  console.log(statehelp)
  console.log(statehelp.content)
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Irrelefant
  • 125
  • 1
  • 1
  • 7

1 Answers1

0

That happens because console.log() is synchronous operation. It won't wait for your api call to happen. So don't use console.log() as a metric for identifying whether your object got populated or not.

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • I see, but the thing is that the first console.log has the whole object with its updated contents, but the second doesn't. – Irrelefant May 08 '20 at 13:11
  • When you log statehelp, is the structure what you expected it to be?. Like the keys content and products are present with required values? – Lakshya Thakur May 08 '20 at 13:14
  • exactly, that's why I'm confused – Irrelefant May 08 '20 at 13:15
  • 1
    @Irrelefant because browser's logs are *lazy*. The first log logs the `statehelp` object to the console. It's properties are loaded freshly everytime you expand it. By the time you expand the object, `.then(result => statehelp.content = result)` would've populated the object. If you log `JSON.stringify(statehelp)` , you'll notice it is empty when it was logged `https://stackoverflow.com/a/17320220/3082296 – adiga May 08 '20 at 13:15
  • Okay, first off thanks for your answer. What would I now need to do if I wanted the contents of "statehelp" in the state of my component? – Irrelefant May 08 '20 at 13:30