Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useState, useEffect } from "react";
export const render = result => match =>
result.pending ? match.pending()
: result.error ? match.error(result.error)
: result.data ? match.data(result.data)
: null // prettier-ignore
export const useMatchFetch = url => {
const [result, setResult] = useState({ pending: true, initial: true });
const [fetchId, setFetchId] = useState(false)
useEffect(() => {
setResult({...result, pending: true})
fetch(url)
.then(response => response.json())
.then(data => setResult({ data, pending: false, initial: false }))
.catch(error => setResult({ error, pending: false, initial: false }));
}, [url, fetchId]);
const refetch = () => setFetchId(!fetchId)
return [result, refetch]
};
const someComponent = () => {
const [result, refetch] = useMatchFetch('http://www.google.com')
if (result.error) {
return <Error error={error} />
}
if (result.pending && result.initial) {
return <Loader />
}
return (
<div>
{result.pending && <Spinner />}
<button onClick={refetch}>Refetch</button>
{JSON.stringify(result.data, undefined, 2)}
</div>
)
}
// or, to get the previous behavior use `const renderMatch = render(result); return renderMatch(....)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.