Skip to content

Instantly share code, notes, and snippets.

@lauslim12
Last active September 2, 2022 01:47
Show Gist options
  • Save lauslim12/8d65eceb8310a5a70a55b07f209849ef to your computer and use it in GitHub Desktop.
Save lauslim12/8d65eceb8310a5a70a55b07f209849ef to your computer and use it in GitHub Desktop.
SWR React Hook to be reusable with as many requests as possible. TypeScript safe!
import { type Key, useSWR } from 'swr';
/**
* Fetcher is created to be used with `useSWR` hook.
*
* @param url - URL of the endpoint.
* @returns JSON response of the resulting request.
*/
const fetcher = async (url: string) => {
const res = await fetch(url);
// If the status code is not in the range 200-299,
// we still try to parse and throw it.
if (!res.ok) {
const error = await res.json();
throw error;
}
const parsed = await res.json();
// We assume the response to be in this format:
// {
// "status": "success",
// "message": "Successfully fetched data!",
// "data": []
// }
return parsed.data;
};
/**
* Hook to call a `GET` request with Vercel's `useSWR` for performance and reactive
* applications. It is required to be supplied with 'T' for generic type safety.
*
* @example
* const { data: me, error } = useRequest('/api/v1/users/me');
* if (data) return <UserProfile user={me}} />
* if (error) return <InternalServerError />
*
* @param key - Key argument to the SWR.
* @returns An object consisting of the data, a boolean value whether
* it is loading or not, an error if it exists, and a mutator function
* to update the state again.
*/
const useRequest = <T>(key: Key) => {
const { data, error, mutate } = useSWR<T>(key, fetcher);
return {
data,
isLoading: !data && !error,
error,
mutate,
};
};
export default useRequest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment