Created
August 20, 2019 16:42
-
-
Save mtho11/ca7c267ccf8314a538bd6b8bb1377c07 to your computer and use it in GitHub Desktop.
React.js: Fetching with Hooks
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 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