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!
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);