Last active
June 16, 2019 09:10
Star
You must be signed in to star a gist
useMatchFetch alternative to https://dev.to/joelnet/react-i-really-wish-this-is-how-i-could-write-components-1k4j
This file contains 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
| 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] | |
| }; |
This file contains 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
| 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