Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!