0

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;
});

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.