Skip to content

Instantly share code, notes, and snippets.

@patroza
Last active June 16, 2019 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save patroza/4488f8fa2b80ee723dafd102e312b888 to your computer and use it in GitHub Desktop.
Save patroza/4488f8fa2b80ee723dafd102e312b888 to your computer and use it in GitHub Desktop.
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