[javascript] Javascript: Fetch DELETE and PUT requests

I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.

So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.

This question is related to javascript reactjs fetch http-delete http-put

The answer is


Just Simple Answer. FETCH DELETE

function deleteData(item, url) {
  return fetch(url + '/' + item, {
    method: 'delete'
  })
  .then(response => response.json());
}

Here is good example of the CRUD operation using fetch API:

“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW

Here is the sample code I tried for PATCH or PUT

function update(id, data){
  fetch(apiUrl + "/" + id, {
    method: 'PATCH',
    body: JSON.stringify({
     data
    })
  }).then((response) => {
    response.json().then((response) => {
      console.log(response);
    })
  }).catch(err => {
    console.error(err)
  })

For DELETE:

function remove(id){
  fetch(apiUrl + "/" + id, {
    method: 'DELETE'
  }).then(() => {
     console.log('removed');
  }).catch(err => {
    console.error(err)
  });

For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.


Ok, here is a fetch DELETE example too:

fetch('https://example.com/delete-item/' + id, {
  method: 'DELETE',
})
.then(res => res.text()) // or res.json()
.then(res => console.log(res))

Some examples:

async function loadItems() { try { let response = await fetch(https://url/${AppID}); let result = await response.json(); return result; } catch (err) { } }

async function addItem(item) {
    try {
        let response = await fetch("https://url", {
            method: "POST",
            body: JSON.stringify({
                AppId: appId,
                Key: item,
                Value: item,
                someBoolean: false,
            }),
            headers: {
                "Content-Type": "application/json",
            },
        });
        let result = await response.json();
        return result;
    } catch (err) {
    }
}

async function removeItem(id) {
    try {
        let response = await fetch(`https://url/${id}`, {
            method: "DELETE",
        });
    } catch (err) {
    }
}

async function updateItem(item) {
    try {
        let response = await fetch(`https://url/${item.id}`, {
            method: "PUT",
            body: JSON.stringify(todo),
            headers: {
                "Content-Type": "application/json",
            },
        });
    } catch (err) {
    }
}

Here are examples for Delete and Put for React & redux & ReduxThunk with Firebase:

Update (PUT):

export const updateProduct = (id, title, description, imageUrl) => {
    await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
  method: "PATCH",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title,
    description,
    imageUrl,
  }),
});

dispatch({
  type: "UPDATE_PRODUCT",
  pid: id,
  productData: {
    title,
    description,
    imageUrl,
  },
});
};
};

Delete:

export const deleteProduct = (ProductId) => {
  return async (dispatch) => {
await fetch(
  `https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
  {
    method: "DELETE",
  }
);
dispatch({
  type: "DELETE_PRODUCT",
  pid: ProductId,
});
  };
};

For put method we have:

const putMethod = {
 method: 'PUT', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 body: JSON.stringify(someData) // We send data in JSON format
}

// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

Example for someData, we can have some input fields or whatever you need:

const someData = {
 title: document.querySelector(TitleInput).value,
 body: document.querySelector(BodyInput).value
}

And in our data base will have this in json format:

{
 "posts": [
   "id": 1,
   "title": "Some Title", // what we typed in the title input field
   "body": "Some Body", // what we typed in the body input field
 ]
}

For delete method we have:

const deleteMethod = {
 method: 'DELETE', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 // No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod) 
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

In the url we need to type the id of the of deletion: https://www.someapi/id


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to fetch

Using Axios GET with Authorization Header in React-Native App Retrieve data from a ReadableStream object? Javascript: Fetch DELETE and PUT requests How do I POST with multipart form data using fetch? What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate PHP PDO with foreach and fetch Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused Trying to get property of non-object in php pdo: get the columns name of a table

Examples related to http-delete

Axios Delete request with body and headers? Javascript: Fetch DELETE and PUT requests Body of Http.DELETE request in Angular2 What REST PUT/POST/DELETE calls should return by a convention? How to send PUT, DELETE HTTP request in HttpURLConnection?

Examples related to http-put

Javascript: Fetch DELETE and PUT requests What is the difference between PUT, POST and PATCH? Should I use PATCH or PUT in my REST API? PHP cURL HTTP PUT