Created
August 19, 2019 12:51
-
-
Save khades/e0b250a2bedf964ff1259d43097057b1 to your computer and use it in GitHub Desktop.
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
// Well, that's version that takes fetch function, and does not create it from passed params | |
enum FetchState { | |
Failed, | |
Ok, | |
AliensAteIt, | |
ProxyFailed, | |
DoneNuthing, | |
Looding, | |
Whoops | |
} | |
function useApi<T>({ callback }: { callback: () => Promise<Response> }) { | |
const [fetchState, setFetchState] = React.useState<FetchState>( | |
FetchState.DoneNuthing | |
); | |
const [data, setData] = React.useState<T | null>(null); | |
React.useEffect(() => { | |
const meh = async function() { | |
setFetchState(FetchState.Looding); | |
try { | |
const response = await callback(); | |
if (!response.ok) { | |
setFetchState(FetchState.Whoops); | |
} else { | |
const data = (await response.json()) as T; | |
setData(data); | |
setFetchState(FetchState.Ok); | |
} | |
} catch (_) { | |
// some logic | |
setFetchState(FetchState.AliensAteIt); | |
} | |
}; | |
}, [callback]); | |
return [data, fetchState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment