Home / Snippets / Updating a resource with the Fetch API from front-end application
Updating a resource with the Fetch API from front-end application cover

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

890

3 years ago

0 comments

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
}
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this