Last active
July 10, 2022 15:55
-
-
Save gabemeola/48b11855daa92af1584c6d867f084872 to your computer and use it in GitHub Desktop.
Better... Fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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