Skip to content

Instantly share code, notes, and snippets.

@arinthros
Created September 7, 2021 20:35
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 arinthros/64dc698d5a367534b63cef4f98d6c2b9 to your computer and use it in GitHub Desktop.
Save arinthros/64dc698d5a367534b63cef4f98d6c2b9 to your computer and use it in GitHub Desktop.
React router data fetching demo
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