Created
November 29, 2022 22:18
-
-
Save jinsley8/62c97abbb7ade910be1ee069994522b9 to your computer and use it in GitHub Desktop.
A hook that uses fetch to fetch data
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
enum Method { | |
GET = 'GET', | |
POST = 'POST', | |
PUT = 'PUT', | |
PATCH = 'PATCH', | |
DELETE = 'DELETE', | |
} | |
const useFetch = (endpoint: string, apiKey?: object) => { | |
const defaultHeader = { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}; | |
const customFetch = async ( | |
url: string, | |
method: Method = Method.GET, | |
body?: object, | |
headers: object = apiKey ? Object.assign(defaultHeader, apiKey) : defaultHeader | |
) => { | |
try { | |
const config: any = { | |
method, | |
headers, | |
}; | |
if (typeof body != 'undefined') { | |
Object.assign(config, JSON.stringify(body)); | |
} | |
const res = await fetch(url, config); | |
const data = await res.json(); | |
return data; | |
} catch (err) { | |
console.error(err); | |
throw err; | |
} | |
}; | |
const get = () => { | |
return customFetch(endpoint); | |
}; | |
const post = (body?: object) => { | |
if (!body) throw new Error('To make a POST request you must provide the body.'); | |
return customFetch(endpoint, Method.POST, body); | |
}; | |
const put = (body?: object) => { | |
if (!body) throw new Error('To make a PUT request you must provide the body'); | |
return customFetch(endpoint, Method.PUT, body); | |
}; | |
const patch = (body?: object) => { | |
if (!body) throw new Error('To make a PATCH request you must provide the body'); | |
return customFetch(endpoint, Method.PATCH, body); | |
}; | |
const del = () => { | |
return customFetch(endpoint, Method.DELETE); | |
}; | |
return { | |
get, | |
post, | |
patch, | |
put, | |
del, | |
}; | |
}; | |
export default useFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment