0

YES I know this is a common question, however I can not seem to get provided examples to work in my situation... I have an empty array in my state:

constructor(props) {
        super(props);
            this.state = {
                selectedItems: []
             }
         }

And I want to simply add items to that array with this code (it's in a function):

this.setState( {
    selectedItems:[...this.state.selectedItems, data]
  })

data in this case being the thing added to the state array.

The problem I encounter(when I console.log this.state) is that the first occurrence of this push to the array never works. SO for example, if I pushed to it 4 different times, only three will be in the state array and it will not register the first time I tried.

I am lost as to why. Any help appreciate. =)

Xavi Jimenez
  • 314
  • 1
  • 3
  • 16
TomK
  • 117
  • 1
  • 12
  • 1
    Where do you `console.log(this.state)`? – Clarity Aug 07 '19 at 07:14
  • Just directly below, after the this.setState() call in the same function – TomK Aug 07 '19 at 07:15
  • 2
    try this `this.setState( { selectedItems:[...this.state.selectedItems, data] }, () => console.log(this.state))`. Setting state is asynchronous in React, so it happens after some time.. you need to do a callback as second argument, to know the new state – boop_the_snoot Aug 07 '19 at 07:15
  • 1
    Are you trying to console.log after the setState? If so add the console.log in a function as the 2nd argument of setState. – Jon B Aug 07 '19 at 07:15
  • Possible duplicate of [Reactjs setState asynchronous](https://stackoverflow.com/questions/54029244/reactjs-setstate-asynchronous) – Arnaud Christ Aug 07 '19 at 07:19

2 Answers2

3
this.setState( { selectedItems:[...this.state.selectedItems, data] }, () => console.log(this.state))

Try this with the log as the 2nd argument of setState, this will run once the state has been updated

Jon B
  • 2,444
  • 2
  • 18
  • 19
  • Yes thank you very much, I seemed to have been using the console log in the wrong location as you said – TomK Aug 07 '19 at 07:19
1

If you're logging the state directly after setting it, it will be updated asynchronously. To get the final value you can use setState callback:

this.setState({
  selectedItems: [...this.state.selectedItems, data]
}, () => console.log(this.state))

Clarity
  • 10,730
  • 2
  • 25
  • 35