Created
September 7, 2021 20:35
-
-
Save arinthros/64dc698d5a367534b63cef4f98d6c2b9 to your computer and use it in GitHub Desktop.
React router data fetching demo
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 from 'react' | |
import { useRouteMatch } from 'react-router-dom' | |
import { statusTypes } from '@youversion/react' // Helper object for status enums 'pending', 'idle', 'resolved', 'rejected' | |
import { getThing } from './api-methods' | |
function MyComponent() { | |
const { path } = useRouteMatch() | |
const [loadingStatus, setLoadingStatus] = React.useState(statusTypes.PENDING) | |
const [data, setData] = React.useState() | |
React.useEffect(() => { | |
async function loadData() { | |
setLoadingStatus(statusTypes.PENDING) | |
try { | |
const response = await getThing() // Use whatever your data function is. | |
setData(response) | |
setLoadingStatus(statusTypes.RESOLVED) | |
} catch (error) { | |
setLoadingStatus(statusTypes.REJECTED) | |
} | |
} | |
loadData() | |
}, [path]) // Effect will run on initial load, and when `path` changes. | |
if (loadingStatus === statusTypes.PENDING) { | |
return <LoadingSpinnerThing /> | |
} | |
if (loadingStatus === statusTypes.REJECTED) { | |
return <SomeErrorThing /> | |
} | |
return ( | |
<> | |
{ data.length ? data.map(/* do stuff here */) : 'no data' } | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment