1

I need to drop a picture, then upload it to the server and update the interface. I have a problem, the lifecycle method componentDidUpdate is beginning to be updated infinitely, in the condition I indicated to compare this.state with the prevState. (PrevState is undefined, I can not understand why).

I put my code in the sandbox, I hope it will be clear. https://codesandbox.io/s/headless-smoke-4xxi2

3 Answers3

2

WHY: This seems like a reference/variable memory address issue.

When you are storing to itemsList you are creating a new reference because you are receiving a non-primitive value from the api. JS always operates with references when it comes to non-primitive values. So, your if (this.state.itemsList !== prevState.itemsList) will always return true because itemsList is an array which is non-primitive data set which means JS is not checking it's values but only the references.

I see two solutions atm in this case:

  1. Prevent updating the state if the values are same

OR

  1. Check by values with appropriate checker function in this statement if (this.state.itemsList !== prevState.itemsList)

Hope I was able to explain. Cheers!

ShocKwav3_
  • 1,670
  • 6
  • 22
  • 44
0

You are not using correct parameter. See componentDidUpdate takes prevProps as first argument and prevState as second.

enter image description here

Try this

componentDidUpdate(prevProps, prevState)
jank
  • 840
  • 4
  • 7
  • It will still loop infinitely if the api data length and the state data length is same – ShocKwav3_ Jul 11 '19 at 11:28
  • Good catch! I did not notice either. But regardless of that, the code will still hit infinite loop because `itemsList` is an `array` which is a non-premitive dataset :) – ShocKwav3_ Jul 11 '19 at 11:36
  • @ShocKwav3_ you should check lengths of array if you can or do deep comparison – jank Jul 11 '19 at 11:42
  • checking lengths will fail as well when the api returns some data that has same length as the state data. Deep comparison is what I have suggested in my answer – ShocKwav3_ Jul 11 '19 at 11:50
0

prevState is the second argument to componentDidUpdate. Try -

componentDidUpdate(prevProp, prevState) {
    console.log(this.state.itemsList, prevState.itemsList);
    if (this.state.itemsList !== prevState.itemsList) {
      // if you remove the comment from this method, then an infinite update will begin
      //
       this.updateItemList();
    }
  }
Monika Mangal
  • 1,665
  • 7
  • 17