Home > Software engineering >  How to update an object and set the state with new object values using React or React Native
How to update an object and set the state with new object values using React or React Native

Time:11-30

I am trying to update an object which is stored in my useState hook 'items'. Code block 1 does not work however code block 2 does. The only thing I did was put my items in a new variable. Can someone explain why code block 1 does not work however code block 2 does work.

Does NOT work

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  items[objIndex] = folder;

  // set state with update
  setItems([...items]);
};

Below works

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // put state into variable
  const myItems = [...items]
  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  myItems[objIndex] = folder;

  // set state with update
  setItems(myItems);
};

CodePudding user response:

items[objIndex] = folder;

You should never update state directly like this. React assumes you always use the "set" functions to update your state, and will not know when to re-render your components if you modify state directly.

https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

CodePudding user response:

  // update object
  items[objIndex] = folder;

I believe this is the problem. I actually never tried to change the state itself (I've always assumed it's read-only).

I will test this further later to be sure. But usually you don't edit the state directly (the state means the items variable). Either you 1) create an items1 such as items1 = { ...items } and then setItems(items1[objIndex] = folder) or you follow your approach in the second code snippet.

  • Related