Skip to content Skip to sidebar Skip to footer

React Updating When Array Filters But Not When An Element Is Added

I'm trying to simulate a table where I am able to add and remove products, however the component only updates when component is removed but not when I add a new row. I'm using useS

Solution 1:

In React, you should update state by passing a new reference into the state setter. With

let arr = rows
arr.push(obj)

you're setting the state to the same array that's currently in state, and mutating it.

Always avoid mutation with React state. Create a new array and put it into state instead:

setRows([...rows, obj]);

Solution 2:

The following is a state mutation. Pushing an element into the existing state array object and setting it back in state doesn't allow react to diff correctly and re-render.

let arr = rows
arr.push(obj)
setRows(arr)

Solution is to use a functional state update and shallowly copy previous state into a new array and append the new element.

consthandleAddUi = (e) => {
  let obj = createData(rows.length + 1, "test", "a", "b");
  setRows(rows => [...rows, obj]);
}

Solution 3:

Also, make sure you avoid mutation while deleting. You can simply use the splice operator instead of doing filtering and setting the array.

Just use return [...array.splice(i,1)];

//i is going to be the index.

Post a Comment for "React Updating When Array Filters But Not When An Element Is Added"