I have an array inside an object addedCertificates
and I want to push values into it.
const addShift = () => {
setShiftList((prev) => [
...prev,
{
id: shiftList.length,
date: '',
startTime: '',
endTime: '',
addedCertificates: [],
selectedCertificate: '',
},
]);
};
When a button click occurs I want to push the selectedCertificate
into the addedCertificates
array. The function will look something like this:
const addCertificate = (index) => {
const list = [...shiftList];
list[index]['addedCertificates'] = list[index]['selectedCertificate'];
setShiftList(list);
console.log('shiftList from add certificate', shiftList)
}
Right now the addedCertificates just get replaced with the selectedCertificate, but I want to keep the already added certificates.
I cant seem to use .push
on the array like this:
list[index]['addedCertificates'].push(list[index]['selectedCertificate']);
Does any one know how I can push values to this array?
2
Answers
I think you can use the push function in your case.
Because you have created a new list by const
list = [...shiftList];
So React knows the list has been updated and will re-render the page.
In other cases, you can try as follows
Hope it can be helpful for you
You can do something like this: