0

This is a really strange issue I've been trying to debug today; When the component mounts I'm getting the notifications to display them like this

  componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      }
    );
  }

And then I tried to console log the notifications by adding this

  componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      },
      () => {
        console.log(this.state.notifications);
        console.log(this.state.notifications.length);
      }
    );
  }

And what I get is this!

first console.log()

[]
0: {title: "Success", text: "You have successfully created a new game!", destination: {…}, type: "GameCreated"}
length: 1
__proto__: Array(0)

second console.log()

0

Shouldn't the array length be 1 instead of 0? I do have an element in that array. Also when I try to get the first value to that array it returns undefined.

Thanks for taking the time to read this and help out!

3 Answers3

3

When you output an object with console.log its state may evolve and you are not necessarily seeing the state of this object at the time console.log was called but only at the time it was expanded in the console view. Which is not the case with primitives. Most probable scenario: when calling console.log the array was empty, with a length of 0. When you expand the Array log in the console view you will see it populated even if it was not at the time it was logged.

255kb - Mockoon
  • 6,657
  • 2
  • 22
  • 29
  • 2
    to verify this, you can change the line to `console.log([ ...this.state.notifications ])`, so that the logged object will not be mutated before you're able to check it – Andrew Ault Apr 07 '20 at 13:39
  • thats actually very true, i did change my console log with what you mentioned and it returns an empty array as well. Thanks! – Abderrahmen Mhemed Apr 07 '20 at 13:45
0

I did the same test and it works correctly on my computer, it logs length as 1. Maybe there is something else in your code that is causing a side effect

HermitCrab
  • 3,194
  • 1
  • 11
  • 10
0

In your browser, console.log is working as an async function.

Check this question: Is Chrome's JavaScript console lazy about evaluating arrays?

To avoid this, you can use JOSN.parse( JSON.stringify(MutableData) ) like below;

componentDidMount() {
    this.setState(
      {
        notifications: this.props.notifications,
      },
      () => {
        console.log(JSON.parse(JSON.stringify(this.state.notifications)));
        console.log(this.state.notifications.length);
      }
    );
  }
Diamond
  • 3,470
  • 2
  • 19
  • 39