how to delete a single item using axios in react

前端 未结 2 2036
别那么骄傲
别那么骄傲 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条回答
  •  萌比男神i
    2021-01-28 20:43

    Thanks @FranklinFarahani. I had to write an answer as it is too long. I have changed my get and post method and managed to fix the delete method. I use the unique key that firebase is creating per post to delete each item. I get that inget method. This is the entire code.

     // The individual post component
      const Post = props => (
        // use the key as an id here
        

    {props.title}


    {props.content}

    ); // The Post lists component class Posts extends React.Component { state = { posts: [], post: { id: "", title: "", content: "" }, indexes: [] }; componentDidMount() { const { posts } = this.state; axios .get("firebaseURL/posts.json") .then(response => { // create an array to hold th unique id as key and post as value using Object.entries const retrievedPosts = []; for (const [key, value] of Object.entries(response.data)) { const post = { id: key, title: value.title, content: value.content }; // add allposts to the array here retrievedPosts.push(post); } // update state this.setState({ posts: retrievedPosts }); console.log(retrievedPosts); }); } handleChange = event => { const [name, value] = [event.target.name, event.target.value]; // const value = event.target.value; const { post } = this.state; const newPost = { ...post, [name]: value }; this.setState({ post: newPost }); }; handleSubmit = event => { event.preventDefault(); const { posts } = this.state; // use this as a temporary id for post method const postIndex = posts.length + 1; const post = { id: postIndex, title: this.state.post.title, content: this.state.post.content }; axios .post("firebaseURL/posts.json", post) .then(response => { const updatedPosts = [ ...posts, { id: post.id, title: post.title, content: post.content } ]; // update state this.setState({ posts: updatedPosts }); console.log(posts); }); }; handleDelete = postId => { event.preventDefault(); // get a copy of the posts const posts = [...this.state.posts]; // in delete method use postId to create a unique url for the post to be deleted axios .delete( "firebaseURL/posts/" + postId + ".json" ) .then(response => { //update state this.setState({ posts: posts }); }); }; render() { let posts =

    No posts yet

    ; if (this.state.posts !== null) { posts = this.state.posts.map(post => { return ( this.handleDelete(post.id)} /> ); }); } return ( {posts}