Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda