DEV Community

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

Posted on • Edited on

FETCH API Part 3/4 (PUT) 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 PUT request is way easier than you think.

SIMPLEST WAY TO USE FETCH FOR PUT REQUEST

fetch(YOUR_URL, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(YOUR_DATA_THAT_YOU_WANT_TO_PUT)
})
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 PUT

  • 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.

  • 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()

  • YOUR_DATA_THAT_YOU_WANT_TO_PUT is a JavaScript object.

COMPLETE GUIDE FOR USING FETCH (PUT)

PROMISE VERSION

const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true};

fetch(YOUR_URL, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(myDataObject)
})
.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

What's happening on the code?

We have the data inside the varriable myDataObject that we want to put. Now we passed the URL where we want to put, 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 PUT and also mentioned that our 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 puts our data to that url 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 PUT request with FETCH so easily.

ASYNC AWAIT VERSION

//data that you want to send
const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true };

const putData = async ( ) =>{
   const response = await fetch(YOUR_URL, {
       method: 'PUT', 
       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);
};
putData( );
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 putData and then called it. Do NOT worry. I'll explain all about async and await on Nov 6th 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.

//your data to send
const myDataObject = {
    "userId": 1,
    "id": 1,
    "title": "The blog of SilvenLEAF",
    "completed": false
};


const putData = async ( ) =>{
   const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
       method: 'PUT', 
       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);
};
putData( );
Enter fullscreen mode Exit fullscreen mode

PROMISE VERSION

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

//your data to send
const mySecondDataObject = {
    "userId": 1,
    "id": 1,
    "title": "The blog of SilvenLEAF",
    "completed": false
};



fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(mySecondDataObject)
})
.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!!

FETCH API PART 4/4 (DELETE)(Series) coming on 6th Nov, 2020

NEXT BLOG is coming on 6th Nov, 2020

on ASYNC and AWAIT

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 2/4 (POST) (easiest explanation)

Next Blog

FETCH API PART 4/4 (DELETE) (easiest explanation)

Top comments (2)

Collapse
 
opentechconsult profile image
OpenTech-Consult

I love your article. Very simple English easy to understand. And I love the state of mind the kindness. Looking forward to reach out to you on LinkedIn. Maybe you can help me on my portfolio projects.

Collapse
 
silvenleaf profile image
SilvenLEAF

Thank you! So nice of you. Really appreciate it. I'd be glad to connect with you too.

Yep, I'll do my best to help you. Feel free to ask if you need anything from me.

Also, if there is any concept relating to Nodejs, React, JavaScript etc (see my skills) that you do not understand, let me know. I'll create an article on that too.

Thank you OpenTechConsult!! Wish you a great day ahead!!