skip to Main Content

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


  1. 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

    list[index]['addedCertificates'] = [...list[index]['addedCertificates'], list[index]['selectedCertificate']];
    

    Hope it can be helpful for you

    Login or Signup to reply.
  2. You can do something like this:

     const addCertificateToShiftList = (index, objectToPush) => {
    
        setShiftList(prev => {
         const updatedShiftList = [...prev];
         const updatedShift = { ...updatedShiftList[index] };
         updatedShift.addedCertificates.push(objectToPush);
         updatedShiftList[index] = updatedShift;
         return updatedShiftList;
       });
     };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search