Skip to content

Instantly share code, notes, and snippets.

@SergioGeeK7
Created February 5, 2020 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergioGeeK7/06978a49df67c871efa7ace76c1e61d1 to your computer and use it in GitHub Desktop.
Save SergioGeeK7/06978a49df67c871efa7ace76c1e61d1 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
const useFetch = url => {
const [state, setState] = useState({
loading: true,
error: false,
data: [],
});
useEffect(() => {
fetch(url)
.then(res => {
if (!res.ok) {
throw new Error(res.status);
}
return res.json();
})
.then(data => setState({ loading: false, error: false, data }))
.catch(error => setState({ loading: false, error, data: [] }));
}, []);
return state;
};
const Loading = () => <p>Loading</p>;
const Error = error => <p>Oops! Something went wrong: {error}</p>
const List = ({ items, renderItem }) => (
<ul>
{data.map(item => <li key={item.id}>{renderItem(item)}</li>)}
</ul>
);
const DataList = () => {
const { loading, error, data } = useFetch("/mock-data");
return (
<>
{ loading && <Loading /> }
{ error && <Error error={error} />}
{ data.length && <List items={data} renderItem={item => item.label} /> }
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment