Created
February 5, 2020 20:16
-
-
Save SergioGeeK7/06978a49df67c871efa7ace76c1e61d1 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, { 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