Last active
December 20, 2024 15:43
-
-
Save esaramago/6d91d53d9a87c6b432cea726c0d81e14 to your computer and use it in GitHub Desktop.
Fetch API Util
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 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