Home > OS >  Is this the correct way to update a propery in objects array state
Is this the correct way to update a propery in objects array state

Time:01-03

I've got the code below and i wanna update name property in the object that has id 1. I'm updating with the code objArray[1].name = "Xxx". It perfectly works but is this correct? Should i use prevState with setObjArray. That looked so much easier what you think?

const [objArray, setObjArray] = useState([
    {
            id:1,
            name:"Eren"
    },
    {
            id:2,
            name:"Eren2"
    },
    {
            id:3,
            name:"Eren3"
    }

])

CodePudding user response:

No this is not advisable. You have the useState second array element (setObjArray) for updating state. Read documentation for React useState . There are two basic ways but there isn't much difference. First method;

  const changeName = (id, newName) => {
    // map through the array and change the name of the element with the id you are targeting
    const changedArr = objArray.map((element) => {
      if (element.id === id) {
        return {
          ...element,
          name: newName,
        };
      } else {
        return element;
      }
    });
    // set the returned array as you new state 
    setObjArray(changedArr)
  };

Second method;

  • You have access to the previous state. This way you can make changes on the previous state and return the new array as your new state.
 const newChangeName = (id, newName) => {
    setObjArray((prev) => {
      // map through the array and change the name of the element with the id you are targeting
      // set the returned array as you new state
      return prev.map((element) => {
        if (element.id === id) {
          return {
            ...element,
            name: newName,
          };
        } else {
          return element;
        }
      });
    });
  };

Hope this helped.

CodePudding user response:

There are many ways to do this. Let me share one way to do this:

  1. Make a shallow copy of the array
let temp_state = [...objArray]; 
  1. Make a shallow copy of the element you want to mutate
let temp_element = { ...temp_state[0] };
  1. Update the property you're interested in
temp_element.name = "new name";
  1. Put it back into our array. N.B. we are mutating the array here, but that's why we made a copy first
temp_state[0] = temp_element;
  1. Set the state to our new copy
setObjArray(temp_state);
  • Related