im trying to add items to the empty array selectedProducts, but every item i add bees 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
im trying to add items to the empty array selectedProducts, but every item i add bees 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
Share
Improve this question
asked Aug 26, 2019 at 11:38
David ZagorskyDavid Zagorsky
731 silver badge7 bronze badges
2
- Hi David, check my solution and let me know if that helps. – ravibagul91 Commented Aug 27, 2019 at 1:39
- 1 thanks!!!! i cant believe how simple it was :) – David Zagorsky Commented Aug 27, 2019 at 17:13
3 Answers
Reset to default 5You can simply do this,
this.setState({
selectedProducts: [...this.state.selectedProducts , item]
});
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'}
});
handleQuantityChange = item => {
const {selectedProducts} = this.state
const carsSelected = [...selectedProducts,item]
this.setState(
{selectedProducts:carsSelected}
);