Created
July 18, 2023 02:59
-
-
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
This file contains hidden or 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
// 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