I am trying to update an object array but even though the correct values are passed to the function, the array remains blank. If I try add a second object, then somehow the first one gets added and I'm not sure what I'm doing wrong.
const [qualifications, setQualifications] = useState([{}]);
function handleAddQualification(values: any) {
console.log(values);
console.log(qualifications);
setQualifications((prev) => {
return [...prev, values];
});
console.log(qualifications);
}
The values that I'm passing get logged correctly and the 2 subsequent logs of qualifications both show an empty array of objects.
I simplified the object so in my screen shot I added 'one' and the value logs correctly, but the qualifications array remains blank. If I add a second entry of 'two' then for some reason it adds 'one' to the array.
Please share some insight as to what is going on here?
Here is example how event loop works :)
In your case:
handleAddQualification
values
, qualifications
setQualifications
to queue as async operationqualifications
again with the same result as from step 3setQualifications
setQualifications
updates qualifications
Take a look here for better understanding https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
The state update calls are asynchronous and you can't see them by logging just after update call.
qualifications
tointerface Qual {
subject?: string;
level?: string;
other?: string
}
const [qualifications, setQualifications] = useState<Qual[]>([]);
useEffect(() => {
console.log({qualifications});
}, [qualifications])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.