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

145
Visualizações
ReactJS: useState for array of object

I have a form with onChange, in the onChange function I need to save values.

const [choosenVar, setChoosenVar] = useState([
    {
      posto1: { name: '', value: '' },
    },
    {
      posto2: { name: '', value: '' },
    },
    {
      posto3: { name: '', value: '' },
    },
    {
      posto4: { name: '', value: '' },
    },
    {
      posto5: { name: '', value: '' },
    },
    {
      posto6: { name: '', value: '' },
    },
  ]);


  const onChange = event => {
    const { name, value, id } = event.target;
    // setchoosenVar({ ...choosenVar, [`posto${id}.nome`]: value });
    const newArr = [...choosenVar];

  };

Now my problem is for every "id" on event.target I should save the name and value in posto"id", How can I do??

Example:

const onChange = event => {
    const { name, value, id } = event.target;
    // name: "Application", value: "appSett", id: "1"
    // in this case I should take: choosenVar.posto1 and set choosenVar.posto1.name = name, choosenVar.posto1.value= value.
  };
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Always make a copy of array state variables first using ... (spread operator).

findIndex() and update the object at the found index. Using Object.keys() we are getting all the keys of the object, since we are only concerned about the first one we check for it.

You might need spread again to make a copy of the object so you do not mutate state somehow

  const onChange = event => {
    const { name, value, id } = event.target;
    const newArr = [...choosenVar];

    let foundIndex = newArr.findIndex(x => { return Object.keys(x)[0] === 
   `posto${id}` });

    let copyObject = {...(newArr[foundIndex][`posto${id}`]) };

    newArr[foundIndex] = { [`posto${id}`] : copyObject };
     setChoosenVar(newArr );
  };

Note: The above assumes that there are no empty objects. And the Id you are looking for exists.

Would like to add that their might be a better way to store your state. An array with elements like might be easier to handle

   {
      posto: { id : 1, name: '', value: '' },
    }

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do following:

    const { name, value, id } = event.target;
    setChoosenVar({
      ...choosenVar,
      ...{`posto${id}`:value}
    })
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