Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to update an object and set the state with new object values using React or React Native

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);
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

  // 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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda