Created
June 1, 2022 15:45
-
-
Save GitaiQAQ/3e4fd6b3b63bcb07061ccd27f59c667c to your computer and use it in GitHub Desktop.
useFetch
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
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