Skip to content

Instantly share code, notes, and snippets.

@khades
Created August 19, 2019 12:51
Show Gist options
  • Save khades/e0b250a2bedf964ff1259d43097057b1 to your computer and use it in GitHub Desktop.
Save khades/e0b250a2bedf964ff1259d43097057b1 to your computer and use it in GitHub Desktop.
// 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