DEV Community

Cover image for FETCH API Part 4/4 (DELETE) by SilvenLEAF
SilvenLEAF
SilvenLEAF

Posted on • Updated on

FETCH API Part 4/4 (DELETE) by SilvenLEAF

This is a SERIES


FETCH API Part 1/4 (GET)


FETCH API Part 2/4 (POST)


FETCH API Part 3/4 (PUT)


FETCH API Part 4/4 (DELETE)


Using Fetch Api for DELETE request is way easier than you think.

SIMPLEST WAY TO USE FETCH FOR DELETE REQUEST:

fetch(YOUR_URL, {
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(YOUR_ADDITIONAL_DATA)  //if you do not want to send any addional data,  replace the complete JSON.stringify(YOUR_ADDITIONAL_DATA) with null
})
Enter fullscreen mode Exit fullscreen mode

What's happening here?

Here we are passing 2 arguments into the fetch function, 1st one is YOUR_URL, and 2nd one is an object describing about the request.

  • method: it's telling what type of request it is, here we described it as DELETE

  • Content-Type: it tells what kind of data we are sending. Here it is application/json that means we are sending json data. There are other options too, depending on what we are sending. But our main focus is this one.

Remember: we use it only if we send any additional data, if we are not sending any additional data, replace entire body with null and you do not need this 'Content-Type' header.

  • body: it contains the actual data that we are sending. Here we have to stringify our javascript object if we want to send it. So we used JSON.stringify(). But if you do not want to send any addional data, just type null.

  • YOUR_ADDITIONAL_DATA is a JavaScript object.

COMPLETE GUIDE FOR USING FETCH (DELETE)

PROMISE VERSION

const myDataObject ={ userId: 1}
fetch(YOUR_URL, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(myDataObject)
})
.then(response => {
    return response.json( )
})
.then(data => 
    // this is the data we get after doing the delete request, do whatever you want with this data
    console.log(data) 
);
Enter fullscreen mode Exit fullscreen mode

What's happening on the code?

We have the additional data inside the variable myDataObject that we want to send with our DELETE request. Now we passed the URL where we want to make the DELETE request, as the 1st argument on the fetch function. Then we passed an object as the 2nd argument, it describes more about the request.

Here we described the request as DELETE and also mentioned that our additional data that we will send is a json object using application/json. Then we described the data inside body property. It must be stringified. So we used JSON.stringify( ) to stringify our javascript object. then we are done. It make a DELETE request to that url with that additional data, and then we get a response.

But as we already know that we can not use this response, we need to parse it first. (See my Prev blog describing it in details FETCH API PART 1/4 (GET)). After parsing it, we get the usable data on the data variable. Now that's how we make a DELETE request with FETCH so easily.

ASYNC AWAIT VERSION

//additional data
const myDataObject = { userId: 1 };

const deleteData = async ( ) =>{
   const response = await fetch(YOUR_URL, {
       method: 'DELETE', 
       headers: {
         'Content-Type': 'application/json'
       },
       body: JSON.stringify(myDataObject)
   });

  const data = await response.json( );

  // now do whatever you want with the data  
   console.log(data);
};
deleteData( );
Enter fullscreen mode Exit fullscreen mode

What's happening on the code?

The concept is totally same as the Promise version.

ONE NOTE: To use async and await, we define a function, then we call it. That's why use created a function named deleteData and then called it. Do NOT worry. I'll explain all about async and await on Nov 7th 2020.

Play with these codes to understand it better

ASYNC AWAIT VERSION

Copy-paste this code on your Browser console, (mine is Chrome) and hit enter.

const deleteData = async ( ) =>{
   const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
       method: 'DELETE', 
       headers: {
         'Content-Type': 'application/json'
       },
       body: null
   });

  const data = await response.json( );

  // now do whatever you want with the data  
   console.log(data);
};
deleteData( );
Enter fullscreen mode Exit fullscreen mode

PROMISE VERSION

Copy-paste this code on your Browser console, (mine is Chrome) and hit enter.

fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    },
    body: null
})
.then(response => {
    return response.json( )
})
.then(data => 
    // this is the data we get after putting our data, do whatever you want with this data
    console.log(data) 
);
Enter fullscreen mode Exit fullscreen mode

If you have any questions or If you are stuck

Feel free to reach out to me. You can also contact me on LinkedIN https://www.linkedin.com/in/silvenleaf/ or on Twitter (as @silvenleaf ).

If you wanna know more about me, this is my portfolio website SilvenLEAF.github.io

I'd LOVE to be your friend, feel FREE to reach out to me!!

Next Blogs DATE

  • Nov 6th 2020, async and await

  • Nov 8th 2020, how to use role-based auth system

  • Nov 10th 2020, Change CSS variables with JavaScript

  • Nov 12th, 14th, 16th 2020, Create login signup system with Passport (Series)

  • Nov 18th 2020, How to create Login with Google

  • Nov 20th 2020, How to create Login with Github

  • Nov 22th 2020, How to create Login with LinkedIn

  • Nov 24th 2020, How to create Login with Twitter

  • Nov 26th, 28th, 30th 2020, Password Reset Series (with Node.js and React)

If this blog was helpful to you,

PLEASE give a LIKE and share,

It'd mean a lot to me. Thanks

Prev Blog

FETCH API PART 3/4 (PUT) (easiest explanation)

Next Blog


Async Await (easiest explanation)

Top comments (3)

Collapse
 
larisafrolova profile image
larisafrolova • Edited

Hello!
Thank you for your post!

Could you please help me, I am new with frontend development.
I am making now really simple budget app. When you input your income, it displays on the screen as a line with amount, source and date. I am using Vue.js. There is a button "Delete" in front of every line with income input. When I click to this button, I want only this line to be deleted from my database. I followed your code in your post, but unfortunately when I clicked to the "Delete" button, all my data is gone from the database.

My code for deleting:

deleteIncomeItem (incomeItemId) {

  fetch(this.incomeFormListInApp.fetch, {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(incomeItemId)
  });

  this.incomeReportListInApp = this.incomeReportListInApp.filter((incomeReportListInForLoop) => incomeReportListInForLoop.id !== incomeItemId  );
},
Enter fullscreen mode Exit fullscreen mode

data () {
return {
incomeReportListInApp: [],

  expensesReportListInApp: [],

  incomeFormListInApp: 
  {
    id: 'income',
    placeholderAmount: 'Income',
    placeholderSource: 'Source',
    placeholderDate: 'Date',
    fetch: 'https://mila-s-budget-default-rtdb.firebaseio.com/income-data.json'
  },
Enter fullscreen mode Exit fullscreen mode

Do you have any suggestions why?

Thanks!

Collapse
 
virginiel profile image
VirginieLemaire

Thanks a lot, this is very easy to understand. It will be usefull for sure ;)

Collapse
 
silvenleaf profile image
SilvenLEAF

Really GLAD to know that!! Thank you for your lovely comment! Have an amazing day my sweet friend. And don't hesitate to reach out to me if you ever get stuck or need anything, regarding JavaScript, TypeScript or anything

Wish you ALL THE BEST on your Coding Adventure!!