Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Last active July 10, 2022 15:55
Show Gist options
  • Save gabemeola/48b11855daa92af1584c6d867f084872 to your computer and use it in GitHub Desktop.
Save gabemeola/48b11855daa92af1584c6d867f084872 to your computer and use it in GitHub Desktop.
Better... Fetch
type FetchRes<T> = Response & {
data: T;
};
/**
* A Fetch Request that errors on non 2xx status codes
*/
export default function betterFetch<T>(
input: RequestInfo,
init?: RequestInit
): Promise<FetchRes<T>> {
return fetch(input, init)
.then(async (response) => {
if (response.ok) {
return {
...response,
data: await response.json(),
};
}
throw response;
})
.catch((err: Response) => {
throw err;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment