Skip to content

Instantly share code, notes, and snippets.

@GitaiQAQ
Created June 1, 2022 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitaiQAQ/3e4fd6b3b63bcb07061ccd27f59c667c to your computer and use it in GitHub Desktop.
Save GitaiQAQ/3e4fd6b3b63bcb07061ccd27f59c667c to your computer and use it in GitHub Desktop.
useFetch
function payload<D, E>() {
const arr: { data?: D, error?: E } & ((_: any) => void)[] = [(data) => { arr.data = data }, (error) => { arr.error = error }];
return arr;
}
const useForceUpdate = () => Object.assign.apply(null, useReducer(({ current }) => ({ current: current + 1 }), { current: 0 }).reverse());
function useFetch<D, E, R = { data?: D, error?: E }>(fetcher, deps = []) {
const forceUpdate = useForceUpdate();
const ref = useRef<R>(payload());
useEffect(() => {
fetcher()
.then(...ref.current)
.finally(() => {
forceUpdate();
})
}, [...deps, ref, forceUpdate]);
return ref.current;
}
function Test() {
const { data, error } = useFetch(fetcher.bind(null, "https://api.github.com/repos/vercel/swr"))
if (error) return "An error has occurred.";
if (!data) return "Loading...";
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👁 {data.subscribers_count}</strong>{" "}
<strong>✨ {data.stargazers_count}</strong>{" "}
<strong>🍴 {data.forks_count}</strong>
</div>
);
}
ReactDOM.render(<Test />, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment