Skip to content

Instantly share code, notes, and snippets.

@rgaidot

rgaidot/useStateFetch.js

Last active Jun 11, 2019
Embed
What would you like to do?
useStateFetch
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;
export const useStateFetch = 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);
};
// Example
export const Example = () => {
const render = useStateFetch('https://api.github.com/users/rgaidot');
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
You can’t perform that action at this time.