Home > Blockchain >  update complex array react js useState
update complex array react js useState

Time:12-06

I have a long array. In this array I want to update the qty which is under misc array I have a list of a person, let's say person with index 0 and index 1, each person can have misc with index 0, and index 1 and each misc can have array with index 0 and 1 and I want to update the qty of misc array. Here is an example: https://playcode.io/1028032

import React from 'react';
import  { useState } from 'react';
export function App(props) {
  const[persons,setPersons] = useState([
  {
    id: 1,
    name: "john",
    gender: "m",
    misc: [
      {
        id: 1,
        name: "xxx",
        qty: 1
      },
      {
        id: 2,
        name: "xxx1",
        qty: 1
      }
    ]
  },
  {
    id: 2,
    name: "mary",
    gender: "f",
    misc: [
      {
        id: 1,
        name: "aaa",
        qty: 1
      },
      {
        id: 2,
        name: "bbb",
        qty: 1
      }
    ]
  },
]
)
const updatePersonMiscQty = (personIndex, miscIndex) => {
  
setPersons(persons => {

    const miscItem = persons[personIndex]?.misc?.[miscIndex]

    if (miscItem ) {
       miscItem.qty  = 1;
    }
    return [...persons];
   })
}

  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <a href="" onClick={()=>updatePersonMiscQty(0,0)}>Click</a>
      {console.log(persons)}
    </div>
  );
}

Let's say I passed 0,0 in updatePersonMiscQty(), first 0 is personIndex, and second 0 is miscIndex. so now it should update qty of person with index 0 and misc with index 0. This array. But nothing is rendered.

{
    id: 1,
    name: "john",
    gender: "m",
    misc: [
      {
        id: 1,
        name: "xxx",
        qty: 2
      },

CodePudding user response:

This is reloading the page:

<a href="" onClick={()=>updatePersonMiscQty(0,0)}>Click</a>

You can prevent this by setting the href to "#".

<a href="#" onClick={()=>updatePersonMiscQty(0,0)}>Click</a>

Or you probably want to use a button instead.

<button onClick={()=>updatePersonMiscQty(0,0)}>Click</button>

CodePudding user response:

you just need to change <a> tag to <button> but I also would recommend to create deeply nested copies when trying to update a nested object.

Try immer.js, with it you just specify what has changed at any level of nesting and it will automatically take care of all the changes that need to be handled.https://immerjs.github.io/immer/

  • Related