Skip to content

Instantly share code, notes, and snippets.

@DungGramer
Last active September 4, 2021 04:07
Show Gist options
  • Save DungGramer/19c1073d50be347a1535082f6533fedb to your computer and use it in GitHub Desktop.
Save DungGramer/19c1073d50be347a1535082f6533fedb to your computer and use it in GitHub Desktop.
Simple fetch snippet for Chrome
async function fetcher(
url,
method = 'get',
body = undefined,
headers = {
'Content-Type': 'application/json',
},
) {
try {
const response = await fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(body),
headers: new Headers(headers),
});
const data = await response.json();
return data;
} catch (error) {
return error;
}
}

### GET jsonplaceholder

await fetcher('https://jsonplaceholder.typicode.com/posts')

### POST jsonplaceholder

await fetcher('https://jsonplaceholder.typicode.com/posts', 'post', {
title: 'foo', body: 'bar', userId: 1,

})

### DELETE jsonplaceholder

await fetcher('https://jsonplaceholder.typicode.com/posts/1', 'delete')

### PUT jsonplaceholder

await fetcher('https://jsonplaceholder.typicode.com/posts/1', 'put', {
title: 'foo', body: 'bar', userId: 1,

})

### PATCH jsonplaceholder

await fetcher('https://jsonplaceholder.typicode.com/posts/1', 'patch', {
title: 'foo',

})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment