Created
December 28, 2020 12:31
-
-
Save brunormferreira/05b582df012937fc61765578c0d758a9 to your computer and use it in GitHub Desktop.
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
const localStorageKey = '__bookshelf_token__' | |
function client(endpoint, {body, ...customConfig} = {}) { | |
const token = window.localStorage.getItem(localStorageKey) | |
const headers = {'content-type': 'application/json'} | |
if (token) { | |
headers.Authorization = `Bearer ${token}` | |
} | |
const config = { | |
method: body ? 'POST' : 'GET', | |
...customConfig, | |
headers: { | |
...headers, | |
...customConfig.headers, | |
}, | |
} | |
if (body) { | |
config.body = JSON.stringify(body) | |
} | |
return window | |
.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config) | |
.then(async response => { | |
if (response.status === 401) { | |
logout() | |
window.location.assign(window.location) | |
return | |
} | |
const data = await response.json() | |
if (response.ok) { | |
return data | |
} else { | |
return Promise.reject(data) | |
} | |
}) | |
} | |
function logout() { | |
window.localStorage.removeItem(localStorageKey) | |
} |
import {client} from './api-client'
function create(listItemData) {
return client('list-items', {body: listItemData})
}
function read() {
return client('list-items')
}
function update(listItemId, updates) {
return client(`list-items/${listItemId}`, {
method: 'PUT',
body: updates,
})
}
function remove(listItemId) {
return client(`list-items/${listItemId}`, {method: 'DELETE'})
}
export {create, read, remove, update}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://kentcdodds.com/blog/replace-axios-with-a-simple-custom-fetch-wrapper?ck_subscriber_id=653418166