Posts Learn Components Snippets Categories Tags Tools About
/

Updating a resource with the Fetch API from front-end application

Learn how to update an existing resource using the fetch API in JavaScript the easy and native way.

Created on Aug 30, 2021

860 views

In this snippet, you will learn how to use "fetch" API to update an existing resource from the front-end. The steps are simple so let's get started.
For this example, we will be using "{JSON} Placeholder" which is a "Free fake API for testing and prototyping".
https://jsonplaceholder.typicode.com
Do note that the above API accepts the "posts" resource which means you can use any of the HTTP methods including PUT.

Fetch API update Resource


The code below updates the post with the ID of 1 to have "foo" as the title and "bar" as the body value and assigned to the user with an ID of 1.  The "fetch" function accepts URL as the 1st parameter and the 2nd-second parameter is an object. Do note that the headers are also specified.
fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  body: JSON.stringify({
    id: 1,
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));
The output of the code above will be as follows. Do note that the resource will not be really updated on the server but it will be faked as if.
{
  id: 1,
  title: 'foo',
  body: 'bar',
  userId: 1
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)