This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Delete Data on the Server with fetch in React

    Andy Van SlaarsAndy Van Slaars

    We’ll use fetch to delete items on the server when the client triggers a removal, and update the UI with a success message once the delete operation on the server has succeeded.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Our application handles removing items from the state, but those deletes aren't reflected on the server. If I delete some to dos and then I refresh the browser, those deleted items will come back because they're still persisted on the server.

    00:15 To persist these deletes, I'm going to add another call to fetch by adding another function to the to do service. I'm going to duplicate save to do and we're going to make a few changes to this.

    00:25 First we'll rename it and we'll call this destroy to do. Then we'll update this argument because we don't need the entire to do for delete, we just need it's ID. Now, I'll update my URL because I'm only passing in the ID. I can just reference it directly.

    00:40 Now I'll update the method to be delete and we won't need the body, so we can delete this and we won't receive any JSON back, so we can delete our call to then. With that defined, I'm going to save that and open App.js.

    00:54 Then we're going to have an import for destroy to do and then I'm going to scroll down and find my handle remove method. Here, I'll add a call to destroy to do and I'll pass in our ID and then I'll add a call to then and call this .show temp message to do remove when we get a response from the server. I'll save that.

    01:21 We'll let the browser reload. Now when I delete an item, I'll get the to do remove message. Now if I open up tb.json, we'll see that I have four to dos and the rest have been deleted.

    Discuss

    Discuss