1

How do I remove an object from an array dynamically after clicking the "remove" button.

For example, in the below code the table has n rows. After clicking on a particular remove button, it should delete only that row. Just like a todo list.

But in my case entire table is getting deleted.

const [items,itemList]=useState([]);
 const [companyName,setCompanyName]=useState('');
 const [experience, setExperience]=useState();


//Adding Items to Array after clicking "Add" button
const handleClose=()=>{
        itemList((old)=>{
            return [...old,{companyName,experience}]
          })
         
    }
//Removing Items from Array After clicking Remove button
const removeItem=(index)=>{
         
        itemList((old)=>{
          return old.filter((arrEle,i)=>{
            return (
               
                i!==index
                );
          })
        })
   }

//Displaying Array of objects on UI
<Table  striped bordered hover size="sm">
                                <thead>
                                    <tr>
                                        
                                        <th>Company Name</th>
                                        <th>Experience</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    
                                        {
                                            items.map((item,index)=>{

                                                return(
                                                    <tr>
                                                    <td>{item.companyName}</td>
                                                    <td>{item.experience}</td>
                                                    <td><button onClick={()=>{removeItem(index)}}>Remove</button></td>
                                                    </tr>
                                                )
                                            })
                                        }
                                
                                    
                                   
                                </tbody>
                            </Table>
3
  • Can you better explain the issue you see? I don't see any overt issue with the way you filter by index, that should work. Can you create a running codesandbox that accurately reproduces this issue and link it in your question? Commented May 13, 2021 at 5:39
  • I tested your code by passing in some initial items, and it appears to work fine. Commented May 13, 2021 at 5:48
  • You may confuse yourself working with arrays, objects and maps all under one hood. Just a fore-warning they're all deleted differently. Array.splice(0, 1), delete object["name"], map.delete(index); Commented May 13, 2021 at 6:09

2 Answers 2

1

Issue

The main issue in your code is that you've a bunch of buttons being rendered inside a form and nearly all of them don't specify a button type. The default for buttons is type="submit", so when any of them are clicked they are submitting the form and the form is taking the default submit action which also happens to reload the page. When the page reloads your app reloads and loses the local component state.

Button type attribute

The default behavior of the button. Possible values are:

  • submit: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a <form>, or if the attribute is an empty or invalid value.
  • reset: The button resets all the controls to their initial values, like <input type="reset">. (This behavior tends to annoy users.)
  • button: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element's events, which are triggered when the events occur.

Solution

Explicitly specify the button types.

  • The delete button

     <button
       type="button" // <-- "button" type
       onClick={() => {
         removeItem(item);
       }}
     >
       Remove
     </button>
    
  • The form buttons to submit, reset, and open the modal

     <Button variant="primary" type="submit"> <-- "submit" type
       Submit
     </Button>
    
     <Button
       variant="primary"
       type="reset" // <-- "reset" type
       style={{ margin: '0 20px' }}
     >
       Reset Form
     </Button>
    
     <Button
       variant="primary"
       type="button" // <-- "button" type
       onClick={handleShow}
       style={{ margin: '0 15px' }}
     >
       Add Experience
     </Button>
    

Note: The submit button is still going to submit the form and since you've not any onSubmit callback on the Form component this button, as-is, will cause the page to reload. You will want to add a submit handler and call preventDefault on the onSubmit event object.

const submitHandler = e => {
  e.preventDefault();
  // handle form data or whatever
};

...

<Form onSubmit={submitHandler}>
  ...
Sign up to request clarification or add additional context in comments.

Comments

0

Generally we should not remove any item from array based on it's index. So try to remove items based on unique values:-

  const removeItem = item => {
    itemList(oldList => {
      return oldList.filter((arrEle, i) => arrEle.companyName !== item.companyName);
    });
  };

And pass item in removeItem function like below:-

onClick={() => removeItem(item)}

Add key to tr like below:-

<tr key={`${item.companyName}-${index}`}>

Working demo: https://stackblitz.com/edit/react-cxkbge

5 Comments

Its not working. After few seconds Entire Table is getting deleted. Can you please check whether Iam doing wrong in updating array of objects (or) displaying Items in table on UI
Yes , you are correct but In my case It is reloading again after deletion of items can you suggest me what can be issue for reloading after deletion. Because of that Item is getting deleted and getting displayed again
can you provide all code from your component and edit in question so we can take better look?
@AbhishekKanuganti Please try to include either a running codesandbox that we can debug live or update your question to include a full code example, with data, so that we may create a sandbox and debug it. Without seeing everything your code is doing we can't really say why something is deleting your entire data.
stackblitz.com/edit/… Can you please help me I am getting error here

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.