Skip to content

Instantly share code, notes, and snippets.

@jinsley8
Created November 29, 2022 22:18
Show Gist options
  • Save jinsley8/62c97abbb7ade910be1ee069994522b9 to your computer and use it in GitHub Desktop.
Save jinsley8/62c97abbb7ade910be1ee069994522b9 to your computer and use it in GitHub Desktop.
A hook that uses fetch to fetch data
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