Last active
February 16, 2021 00:48
-
-
Save frankstepanski/d394c02d302285449dabecc3d18bd506 to your computer and use it in GitHub Desktop.
Using fetch API and async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GET: | |
//set the specific API URL | |
const url = 'http://www.example.com/tasks'; | |
const getFetch = async (url) => { | |
const response = await fetch(url); | |
//convert response to Json format | |
const myJson = await response.json(); | |
// return the response | |
return myJson ; | |
} | |
// POST: | |
//set the specific API URL | |
const url = 'http://www.example.com/tasks'; | |
//initialize the data to be posted | |
const data = { | |
userId: 11, | |
id: 2, | |
title: “coding task”, | |
completed: false | |
} | |
//function to make API Call | |
const postFetch = async (url,data) => ( | |
const response = await fetch(url, { | |
method: 'POST', | |
headers: { | |
//type of data | |
'Content-Type': 'application/json' | |
}, | |
//data to be posted on server | |
body: JSON.stringify(data) | |
}); | |
//convert response to Json format | |
const myJson = await response.json(); | |
//return the response | |
return myJson; | |
} | |
//PUT: | |
//set the specific API URL | |
const url = 'http://www.example.com/tasks/5'; | |
//initialize the data | |
const data = { | |
userId: 1, | |
id: 5, | |
title: “hello task”, | |
completed: false | |
} | |
//function to make API Call | |
const putFetch = async (url,data) => { | |
const response = await fetch(url, { | |
method: ‘PUT’, | |
//data to be updated on server | |
body: JSON.stringify(data), | |
headers: { | |
//type of data | |
“Content-type”: “application/json; charset=UTF-8” | |
} | |
}); | |
//convert response to Json format | |
const myJson = await response.json(); | |
//return the response | |
return myJson; | |
} | |
// DELETE: | |
//set the specific API URL | |
const url = 'http://www.example.com/tasks/3'; | |
//function to make API Call | |
const deleteFetch = async (url) => ( | |
const response = await fetch(url, { | |
method: ‘DELETE’ | |
}); | |
//convert response to Json format | |
const myJson = await response.json(); | |
//return the response | |
return myJson ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment