how to delete a single item using axios in react

You are not specifying what your Post component should delete. In other words, the props.delete is not receiving an id to pass up to your parent component. In order to do that, you can change that to () => props.delete(props.id) and then in your parent component you need to have the handleDelete method receive the id of the item you want to target which is the id we passed up earlier from Post.

I don’t know how your server is set up but using the axios request you originally have in your question your code would look like this:

handleDelete = (itemId) => {
    // Whatever you want to do with that item
    axios.delete("url", { params: { id: itemId } }).then(response => {
      console.log(response);
    });

Here’s a CodeSandbox (using some dummy data in the constructor) displaying the item being passed in a console.log() (axios statement is commented out).


EDIT: How to make axios delete requests using Firebase REST API

Oh sorry, I did not see that you were using Firebase. Direct REST requests are a bit different with Firebase. In your configuration the requests should look like this:

axios.delete(`${url}/${firebasePostId}.json`).then(response => {
    console.log(response)
})

This is assuming your Firebase rules allow unauthorized requests (which I strongly advise against, seeing as anyone could send this request).

Please note that firebasePostId is the push key provided by Firebase when you send POST requests to them, and are in fact a great choice of id for your posts. An example of one is -LOLok8zH3B8RonrWdZs which you mentioned in the comments.

For more information on Firebase REST API syntax, check out their documentation.

Leave a Comment

tech