Created
August 24, 2023 11:46
-
-
Save obedparla/a473a9986646a310d2217017ba02247b to your computer and use it in GitHub Desktop.
Simple 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
export function fetchFromUrl<T>( | |
url: string, | |
options: RequestInit, | |
): Promise<T | { error: string }> { | |
return fetch(url, { ...options }) | |
.then((response) => { | |
if (response.ok) { | |
try { | |
return response.json(); | |
} catch (e) { | |
return { error: e }; | |
} | |
} | |
return { error: response.statusText }; | |
}) | |
.catch((error) => { | |
return { error: error }; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment