This gist shows code to create thin wrapper around browser fetch
api and call it as FetchClient
. But first lets see the usage
of GET/POST requests
- Simple get request
FetchClient(url, HttpMethod.GET);
- POST request with Form Data
FetchClient(url, HttpMethod.POST, JSON.stringify(formData), {
'Content-Type': 'application/json',
});
- POST request with custom object like
newEmployeeDTO
FetchClient(url, HttpMethod.POST, JSON.stringify(newEmployeeDTO), {
'Content-Type': 'application/json',
});
export default function FetchClient(
endpoint: string,
method?: HttpMethod,
body?: any,
headers?: Record<string, string>
) {
const { setCookie, getCookie } = useCookies();
// Updated Request Config with cookies
const config = {
method: method ? method : HttpMethod.GET,
headers: {
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
...headers,
},
body: body,
};
// @ts-ignore
return window.fetch(process.env.NEXT_PUBLIC_REACT_APP_BASE_URL + endpoint, config).then(async (response) => {
if (response.status === 401) {
setCookie('redirectURL', location.pathname);
location.replace('/login');
return;
}
if (response.ok) {
return await response.json();
} else {
const errorMessage = await response.text();
return Promise.reject(new Error(errorMessage));
}
});
}