Home > Back-end >  Remove rows from state array
Remove rows from state array

Time:08-12

I have created a dynamic form which can have rows added and removed and are stored in a state array. I need to remove the index passed into the function from the array, without storing a null or empty value.

This is my current code for removing the rows however this simply removes the last row and not the one required at index

 const removeRow = (index) => {
    setLocationRows((current) =>
       current.filter((employee, i) => {
          return index !== i;
       })
     );
   };

This code removes the required index however sets the value to null / empty which messes up when after removing and adding rows.

setLocationsObj((current) => {
  const copy = { ...current };

  delete copy[index];

  return copy;
});

CodePudding user response:

Joe.

Im supposing you have something like this:

const [locationRows, setLocationRows] = useState([]);

const removeRow = (index) => {
   setLocationRows(locationRows.filter((e,i)=> i !== index))
};

If so, try the above code.

For the complete CRUD operation you can use the following:

const addRow = (newRow) => {
  setLocationRows([... locationRows, newRow])
};
const updateRow = (rowData) => {
  setLocationRows(locationRows.map(e => {
    if(e.id === rowData.id) return rowData;
    else return e;
 });
};

I hope this can help you!

CodePudding user response:

I recently had to do something very similar and used the array splice method, as it allows you to remove the element at a specific index.

const removeRow = (index) => {
    setLocationRows((rows) =>
       // create deep copy
       const newRows = JSON.parse(JSON.stringfy(rows));
       // remove 1 element at index
       newRows.splice(index, 1);
       return newRows;
    );
};

If you are dealing with any sort of nested array it's important to create a deep copy of that array, as the const copy = [...rows] method only creates a shallow copy and can cause all sorts of bugs when trying to manipulate the data further.

Hope this helps!

  • Related