Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created December 12, 2019 16:52
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 jamesarosen/f659873bcb9e35a7722df31b4f36d53e to your computer and use it in GitHub Desktop.
Save jamesarosen/f659873bcb9e35a7722df31b4f36d53e to your computer and use it in GitHub Desktop.
Using state machines in hook-based React components
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