pop
pop

Reputation: 257

UI is not updating when array changes React

I have this two functions to update elements in an array. I'll give an example to make it clearer: Array: [['M',1],['S',2],['L',4]]

First function: When I add a pair to this array, it checks if the first index already exists, and if it does, it updates the second index. Let's say I try to add ['M',3], then the array should update to: [['M',4],['S',2],['L',4]]

 const addRow = () => {
      console.log(rows);
      let unique = true;
      rows.forEach((item)=>{  
        if(item[0] == size){
          item[1] = parseInt(item[1]) + parseInt(qty);
          unique = false;
          return;
        }
      })
      if(unique){
        setRows([...rows, [size, qty,rows.length]]);
      }
    };

Second function: remove from a given index in the array.

 const removeRow = (trashId) => {
      row = rows;
      row.splice(trashId,1);
      setRows(row);
    };

So, this two functions work perfectly. The things is, the UI is not displaying changes immediately after updating the array. It would only display them after updating something else. Any idea about what's happening? Thanks!!

Upvotes: 0

Views: 3126

Answers (1)

do thuan
do thuan

Reputation: 475

When update array, you need to use setRows([...row]);. row.splice(trashId,1); will change value of the array, but it does not change row's reference, so that React will not re-render the component.

Upvotes: 3

Related Questions