1

I console.log(this) in a componentDidMount() and I can see everything (props.betAmounts) well formatted and with the data. However, in the same componentDidMount(), when I console.log(this.props.betAmounts) I get an empty object...

This is a codeSandBox with the explicit problem (visible in the console).

https://codesandbox.io/s/726jjqozzq

Edit 726jjqozzq

Thank you for your help !

GuillaumeRZ
  • 2,656
  • 4
  • 19
  • 35
  • 1
    `if(this.state.betAmounts !== undefined || this.state.betAmounts !== null ) { return( )}`. This solution will help you. – Thananjaya S May 17 '18 at 08:31
  • 1
    componentDidMount of parent is mostly called after the child componentDidMount and hence in the child componentDidMount the data isn't actually available since the parent componentDidMount sets the state – Shubham Khatri May 17 '18 at 08:32
  • 1
    Becuase `componentDidMount()` is invoked immediately after a component is mounted So in `index.js` you can use `componentWillMount()` instead of `componentDidMount()` `componentWillMount()` is invoked just before mounting occurs. It is called before `render()`, – Liam May 17 '18 at 08:44

1 Answers1

1

Since you're calling setState from within your componentDidMount you'll see the intermediate state, so on your first render your betAmounts will be the {} from your App state, therefore you'll see the empty object.

The documentation on componentDidMount touches on this

Calling setState() in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state.

This means that since componentDidMount is only called once, it'll display your empty object, on the second pass (from the extra triggered render) it'll be the object you expect.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92