1

I am a beginner at React learning it from an online tutorial. there is an element used in one of the courses which is ... and can be seen in the following code

handleIncrement = (productId)=>{
        const newProducts=[...this.state.products]
        const index= newProducts.findIndex(p=> p.id === productId)
        newProducts[index].count +=1 ;
        this.setState({products : newProducts});
    }

its usage seems to be creating an array from products and passing it to the newProducts which is an array now. could you please explain what exactly do ... and when we need it to use?

nullptr
  • 3,701
  • 2
  • 16
  • 40
Amir Em
  • 37
  • 5

1 Answers1

3

It's called the spread syntax.

In react, you're not supposed to mutate the state directly. So, if you have an array you want to edit, you will first create a copy of the array with the spread syntax, edit the new array, and finally set the state to the edited copy of the array.

Creating a copy with newProducts = this.state.products is not sufficient in this case as both the variables are pointing to the same object in memory and changing newProducts is the same as changing `this.state.products.

nullptr
  • 3,701
  • 2
  • 16
  • 40