Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating object inside multiple nested array form with useState

I build ecommerce website with nextjs ,

I have product form with product data

this is dummy data :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {
    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 }] }
      ],
    });
  };

enter image description here

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading