Skip to content

Instantly share code, notes, and snippets.

@kmylo
Created July 18, 2023 02:59
Show Gist options
  • Save kmylo/202f115e6e78ef3fe165e8e2dde15651 to your computer and use it in GitHub Desktop.
Save kmylo/202f115e6e78ef3fe165e8e2dde15651 to your computer and use it in GitHub Desktop.
A tiny wrapper around fetch() replace-axios-with-a-simple-custom-fetch-wrapper
// A tiny wrapper around fetch(), borrowed from
// https://kentcdodds.com/blog/replace-axios-with-a-simple-custom-fetch-wrapper
export async function client(endpoint, { body, ...customConfig } = {}) {
const headers = { 'Content-Type': 'application/json' }
const config = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
}
if (body) {
config.body = JSON.stringify(body)
}
let data
try {
const response = await window.fetch(endpoint, config)
data = await response.json()
if (response.ok) {
// Return a result object similar to Axios
return {
status: response.status,
data,
headers: response.headers,
url: response.url,
}
}
throw new Error(response.statusText)
} catch (err) {
return Promise.reject(err.message ? err.message : data)
}
}
client.get = function (endpoint, customConfig = {}) {
return client(endpoint, { ...customConfig, method: 'GET' })
}
client.post = function (endpoint, body, customConfig = {}) {
return client(endpoint, { ...customConfig, body })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment