Delete request in React

18,356

So you'll want an onClick handler on your button in the render function. Then in that handler, make a fetch request with the method DELETE to the API url.

handleClick = userId => {
  const requestOptions = {
    method: 'DELETE'
  };

  // Note: I'm using arrow functions inside the `.fetch()` method.
  // This makes it so you don't have to bind component functions like `setState`
  // to the component.
  fetch("/api/users/delete/" + userId, requestOptions).then((response) => {
    return response.json();
  }).then((result) => {
    // do what you want with the response here
  });
}

render () {
    return this.state.usersData.map((user) => {
      return <div className="dropdown" key={user._id}>
        <li>{user.userName}</li>
        <div className="dropdown-content"><Link to={"/privatchatt/"+user.userName+"/"+sessionStorage.getItem("username")} target="_blank"><p>Starta privatchatt med {user.userName}</p></Link>
          <button onClick={() => { this.handleClick(user._id) }} className="delete-btn">Delete</button>
        </div>
      </div>;
    })
  }
}

For the most part, my code above is pretty standard. There's just one really wonky thing that I did on your button element in the render function. I didn't just pass in a reference to handleClick like you normally would. I wrapped it in a function (an arrow function, specifically). That's because we want pass in a parameter that's not the click event to the handleClick function. Then I'm having handleClick pass in the user id as the parameter. This is because we want the function we defined to accept the ID of the user you want to delete.

Share:
18,356
ACS
Author by

ACS

Updated on June 04, 2022

Comments

  • ACS
    ACS almost 2 years

    I have a List on my page that display all registered users from a collection in Mongodb and Now i have created an Admin Panel that I want to be able to delete users with the click of a button but I have no clue about how to construct such a function.

    This is the component that renders users:

    class UsersList extends React.Component {
    constructor(props) {
      super();
      this.state = {
        usersData: []
      };
    }
    
    
    componentDidMount() {
        fetch('http://localhost:3003/api/inlogg').then(function (response) {
          return response.json();
        }).then(function (result) {
          this.setState({
            usersData: result
          });
          }.bind(this))
      }
    
      render () {
        return this.state.usersData.map(function (user) {
                    return <div className="dropdown" key={user._id}>
                      <li>{user.userName}</li>
                      <div className="dropdown-content"><Link to={"/privatchatt/"+user.userName+"/"+sessionStorage.getItem("username")} target="_blank"><p>Starta privatchatt med {user.userName}</p></Link>
                        <button className="delete-btn">Delete</button>
                      </div>
                    </div>;
                  }
                )
              }
            }
    

    Here is my express delete route (Its working with postman, also "users" is the collection name)

        app.delete('/api/users/delete/:id', (req, res, next) => {
      users.deleteOne({ _id: new ObjectID(req.params.id) }, (err, result) => {
        if(err){
          throw err;
        }
        res.send(result)
      });
    });
    

    This is what is in my db:

    { "_id" : ObjectId("5b6ece24a98bf202508624ac"), "userName" : "admin", "passWord" : "admin" }
    { "_id" : ObjectId("5b6edb95fbbd8420e4dd8d20"), "userName" : "Admin", "passWord" : "Admin" }
    { "_id" : ObjectId("5b6eea7f0becb40d4c832925"), "userName" : "test4", "passWord" : "test4" }
    

    So what i want to create a fetch delete request that goes off when i press a delete button from my React front-end

  • Antony Sampath Kumar Reddy
    Antony Sampath Kumar Reddy over 4 years
    Hey bwalshy,Thanks a lot ...I was struggling to implement delete functionality ..with your answer.I got the solution.