Created
December 12, 2019 16:52
-
-
Save jamesarosen/f659873bcb9e35a7722df31b4f36d53e to your computer and use it in GitHub Desktop.
Using state machines in hook-based React components
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
const STATUSES = { | |
initial: {}, | |
fetching: { showLoadingIndicator: true }, | |
fetched: { showResults: true }, | |
error: { showError: true }, | |
} | |
function Foo() { | |
const [status, setStatus] = useState(STATUSES.initial) | |
const [results, setResults] = useState(null) | |
useEffect(() => { | |
async function fetchFoos() { | |
setStatus(STATUSES.fetching) | |
try { | |
const foos = await fetch('/foos') | |
setResults(foos) | |
setStatus(STATUSES.fetched) | |
} catch () { | |
setStatus(STATUSES.error) | |
} | |
} | |
fetchFoos() | |
}, [setStatus, setResults]) | |
return ( | |
<div class='foos'> | |
{status.showLoadingIndicator && <Loading />} | |
{status.showResults && results.map(foo => <span>foo.name</span>)} | |
{status.showError && <ErrorMessage>Could not load foos</ErrorMessage>} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment