how to delete a single item using axios in react

前端 未结 2 2034
别那么骄傲
别那么骄傲 2021-01-28 20:28

I have looked into many articles and posts like this but it does not work in my case.I simply need to delete an item from my post list in my application using axios. In the axio

2条回答
  •  轮回少年
    2021-01-28 20:54

    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.

提交回复
热议问题