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

149
Visualizações
set state for useState hook in a variable with array of objects

So I'm trying to setInputFields into a variable which contains array of objects. The problem is that array of objects is created in a for loop

const [inputFields, setInputFields] = useState([])
var inputs =[];
for(var i =0; i<exerciseNames.length; i++) {
    inputs.push({id: currWorkoutVolumeId[i], exercise: currExerciseNames[i], sets: sets[i], reps: reps[i], weight: weight[i]})
}
console.log(inputs)
console.log(inputFields)

Where each value in object is an array. When I console.log inputs I get what I want:

(2) [{…}, {…}]
0: {id: 9898, exercise: 'Squats', sets: 9898, reps: 3, weight: 3}
1: {id: 33311, exercise: 'Bench Press', sets: 33311, reps: 2, weight:2}
length: 2
[[Prototype]]: Array(0)

But when I want to set the state into var inputs I get empty array. How can I set the state, because in my case I'm fetching from database and on one case I can have 10 objects (from exerciseNames.length) and the other 100 objects? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Fetch the data from database asynchronously and append it to the currently stored state as follows.

const [inputFields, setInputFields] = useState([]);

setInputFields((currentInputFields) => {
  let inputs = [];

  for (let i = 0; i < exerciseNames.length; i++) {
    inputs.push({
      id: currWorkoutVolumeId[i],
      exercise: currExerciseNames[i],
      sets: sets[i],
      reps: reps[i],
      weight: weight[i],
    });
  }

  console.log(inputs);

  return [...currentInputFields, ...inputs];
});

console.log(inputFields);

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