Created
June 11, 2019 12:48
-
-
Save marekdano/e7f2621e318854b1db5735bb5fde2379 to your computer and use it in GitHub Desktop.
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
| import React from "react"; | |
| import { useState, useEffect } from "react"; | |
| const render = data => match => | |
| data.pending ? match.pending() | |
| : data.error ? match.error(data.error) | |
| : data.data ? match.data(data.data) | |
| : null // prettier-ignore | |
| export const useMatchFetch = url => { | |
| const [data, setData] = useState({ pending: true }); | |
| useEffect(() => { | |
| fetch(url) | |
| .then(response => response.json()) | |
| .then(data => setData({ data, pending: false })) | |
| .catch(error => setData({ error, pending: false })); | |
| }, [url]); | |
| return render(data); | |
| }; | |
| export const Example = () => { | |
| const render = useMatchFetch("https://swapi.co/api/people/1/?format=json"); | |
| return render({ | |
| pending: () => <div>Loading</div>, | |
| error: err => <div>{err.toString()}</div>, | |
| data: data => <pre>{JSON.stringify(data, null, 2)}</pre> | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment