Skip to content

Instantly share code, notes, and snippets.

@pavankjadda
Last active June 8, 2022 03:45
Show Gist options
  • Save pavankjadda/69e7e4da875e5c2c48f92bd04e1a1d21 to your computer and use it in GitHub Desktop.
Save pavankjadda/69e7e4da875e5c2c48f92bd04e1a1d21 to your computer and use it in GitHub Desktop.
Reusable Fetch Client

Reusable Fetch Client

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

Usage

  1. Simple get request
FetchClient(url, HttpMethod.GET);
  1. POST request with Form Data
FetchClient(url, HttpMethod.POST, JSON.stringify(formData), {
      'Content-Type': 'application/json',
    });
  1. POST request with custom object like newEmployeeDTO
FetchClient(url, HttpMethod.POST, JSON.stringify(newEmployeeDTO), {
      'Content-Type': 'application/json',
    });

FetchClient.ts

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));
		}
	});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment