Home > Mobile >  Update nested Array Object Array in React State
Update nested Array Object Array in React State

Time:09-12

I'm trying to update qty of product onClick event using useState in react, the data that I am updating is nested array-object-array

Below is the example of nested data I want to update the qty from it

let categoriesInfo = [
        {
            catid: 'category-1',
            catName: 'Fun Stuff',
            product: [
                {
                    id : 1,
                    name: 'candy',
                    qty: 0,
                },
                {
                    id : 2,
                    name: 'cookie',
                    qty: 0,
                }
            ]
         },
         {
            catid: 'category-2',
            catName: 'Fun Stuff2',
            product: [
                {
                    id : 1,
                    name: 'candy2',
                    qty: 0,
                },
                {
                    id : 2,
                    name: 'cookie2',
                    qty: 0,
                }
            ]
        }
    ]

I am using useState

const [productData, setProductData] = useState(categoriesInfo);

I am fetching the id and catid on click button from other component in the function x

const x = (data) =>{

        console.log(productData)
        const y = productData.map(obj => {
            if (obj.catid == data.catid && obj.product[1-data.prodid].id == data.prodid) {
                console.log(obj.product[1-data.prodid].name)
                return {...obj.product[1-data.prodid], qty : 2}; //something like this 
            }
            return obj;
        });
        setProductData(y);
    }

CodePudding user response:

Code looks really close, what about this?

        const y = productData.map(obj => {
            // you're not interested, just return obj
            if (obj.catid !== data.catid) return obj;

            // you are interested, return a new object
            return {
               ...obj,
               // iterate over it's products and update the one you want
               product: obj.product.map(product => {
                  if(product.id !== data.prodid) return product
                  return { ...product, qty: 2}
               })
            }
        });

CodePudding user response:

Try like below:

let categoriesInfo = [ { catid: "category-1", catName: "Fun Stuff", product: [ { id: 1, name: "candy", qty: 0 }, { id: 2, name: "cookie", qty: 0 } ] }, { catid: "category-2", catName: "Fun Stuff2", product: [ { id: 1, name: "candy2", qty: 0 }, { id: 2, name: "cookie2", qty: 0 } ] } ];

function App() {
  const [productData, setProductData] = React.useState(categoriesInfo);

  const x = (data) => {
    setProductData((prevProductData) =>
      prevProductData.map((item) =>
        item.catid === data.catid
          ? {
              ...item,
              product: item.product.map((product) =>
                product.id === data.prodid
                  ? { ...product, qty: data.qty }
                  : product
              )
            }
          : item
      )
    );
  };

  return (
    <div>
      <button onClick={() => x({ catid: "category-2", prodid: 2, qty: 4 })}>
        Update value
      </button>
      <div>{JSON.stringify(productData, null, 4)}</div>
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

  • Related