I build ecommerce website with nextjs ,
I have product form with product data
this is dummy data :
{
id: "1",
name: "قميص لاكسوت",
description: "فول كفر خامه قطن ليكرا",
rating: 4,
total_sell: 35,
images: [
{
url: "/public/56774684-c63b-4835-b419-a330a61eeccc.jpeg",
},
{
url: "/public/56774684-c63b-4835-b419-a330a61eeccc.jpeg",
},
{
url: "/public/56774684-c63b-4835-b419-a330a61eeccc.jpeg",
},
],
category: {
name: "قمصان",
gender: "حريمي",
},
sizes: [
{
id: "1",
size: "l",
colors: [
{ id: "1", color: "red", stock: 10 },
{ id: "2", color: "black", stock: 5 },
],
},
{
id: "2",
size: "xl",
colors: [
{ id: "1", color: "blue", stock: 15 },
{ id: "2", color: "white", stock: 50 },
],
},
],
createdAt: new Date("2023-08-12T03:49:42.714+00:00"),
},
i try to add size field and inside i try to add color field
i cann’t reach this colors array
this my code for adding size field
const handleAddSize = () => {
const productCopy = JSON.parse(JSON.stringify(product));
productCopy.sizes = [
...productCopy.sizes,
{ size: "", colors: [{ color: "", stock: 0 }] },
];
setProduct(productCopy);
};
when i try to reach color field with the same way it dosn’t work
const handleAddColors = () => {
setProduct({
...product,
sizes: [
...product.sizes,
{colors: [...product.sizes.colors, { color: "", stock: 0 }] }
],
});
};
I tried serveral way but didn’t work
>Solution :
To add a color to a certain sizes object on your product you need to update an existing element in your sizes array on your product.
The handleAddSize works because you are adding an entirely new size object to your product meaning no updating needed. So you can just spread and add a new object.
The solution:
const handleAddColors = (targetSizeId) => {
setProduct({
...product,
sizes: product.sizes.map((size) => { //Replace size object with new object containing a new color if it is the one we are looking for. Else, return existing size.
if(targetSizeId === size.id) {
return {
...size,
colors: [
...size.colors,
{ color: "", stock: 0 }
]
}
}
return size;
},
});
};
Going forward I recommend using TypeScript whenever you are writing React and NextJS applications. Helps catch and explain these kinds of errors before they happen.