Skip to content

Instantly share code, notes, and snippets.

@abdorah
Last active September 25, 2022 18:07
Show Gist options
  • Save abdorah/a66c2dc8e280dde765045fca359de3fe to your computer and use it in GitHub Desktop.
Save abdorah/a66c2dc8e280dde765045fca359de3fe to your computer and use it in GitHub Desktop.
async fetch class that make it easy to perform http crud request in vanilla js.

Http requests in vanilla JS

This code is a set of basic crud operations to perform using fetch API.

I think that we often make these operation or we use them in various projects. However, we should cease on doing the same thing again. That's why I thought it would be better if I made a class in which I assemble some of the basic operations like in this example. Please remember that this implementation is a simple example and you can make your own or just use this one. To do so, you just need to call each one you need of these methods in your code!

class HttpCrudRequests {
async get(url) {
const res = await fetch(url)
const data = await res.json()
return data
}
async post(url, post) {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
const data = await res.json()
return data
}
async put(url, post) {
const res = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
const data = await res.json()
return data
}
async delete(url, post) {
const res = await fetch(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
const data = await 'Deleted successfully'
return data
}
}
@kingsamadesu
Copy link

Noce, keep going.

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