Skip to content

Instantly share code, notes, and snippets.

@esaramago
Last active December 20, 2024 15:43
Show Gist options
  • Select an option

  • Save esaramago/6d91d53d9a87c6b432cea726c0d81e14 to your computer and use it in GitHub Desktop.

Select an option

Save esaramago/6d91d53d9a87c6b432cea726c0d81e14 to your computer and use it in GitHub Desktop.
Fetch API Util
const API_URL = ''
const fetchApi = async (endpoint: string, options?: object) => {
const response = await fetch(`${API_URL}/${endpoint}`, options)
const data = await response.json()
return {
data,
success: response.ok,
}
}
export default {
get: async (endpoint: string, options?: object) => {
const response = await fetchApi(endpoint, {
...options,
method: 'GET',
})
return response.data
},
post: async (endpoint: string, body: any, options?: object) => {
const response = await fetchApi(endpoint, {
...options,
headers: {
...body.headers,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
method: 'POST',
})
return response
},
put: async (endpoint: string, body: any, options?: object) => {
const response = await fetchApi(endpoint, {
...options,
headers: {
...body.headers,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
method: 'PUT',
})
return response
},
delete: async (endpoint: string, options?: object) => {
const response = await fetchApi(endpoint, {
...options,
method: 'DELETE',
})
return response
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment