David Zagorsky
David Zagorsky

Reputation: 73

how to add items properly to the state (empty array) in reactjs?

im trying to add items to the empty array selectedProducts, but every item i add becomes nested inside the other, my goal is to have one array with all the items selected spread inside. im new to react so examples would be greatly appreciated :)

my state:

state = {
    products: products,
    selectedProducts: [],
    totalPrice: 0
  };

the method:

handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = Object.assign([{...selectedProducts}],item)
    this.setState(
      {selectedProducts:carsSelected}
    );

the result (every 0 represent a nested array that shows one item(car)):

[{…}, id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …]
0:
0:
0:
__proto__: Object
count: 0
description: "High Performance"
id: 4
img: 
name: "BMW"
price: 120000
total: 0
__proto__: Object
count: 0
description: "Kinda Fast"
id: 3
img: 
name: "Maserati"
price: 800000
total: 0
__proto__: Object
count: 0
description: "Extremely Fast"
id: 2
img: 
name: "Bugatti"
price: 3200000
total: 0
length: 1

Upvotes: 2

Views: 5161

Answers (3)

Herat Patel
Herat Patel

Reputation: 798

you don't need to use object.assign and spread operator together.

for array you can use like this

this.setState({
   selectedProducts: [...this.state.selectedProducts , item]
});

for object you can use like this

this.setState({
   selectedProducts: {...this.state.selectedProducts , item: '123'}
});

Upvotes: 1

ravibagul91
ravibagul91

Reputation: 20765

You can simply do this,

this.setState({
   selectedProducts: [...this.state.selectedProducts , item]
});

Upvotes: 5

Nikola Diklich
Nikola Diklich

Reputation: 516

handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = [...selectedProducts,item]
    this.setState(
      {selectedProducts:carsSelected}
    );

Upvotes: 0

Related Questions