Skip to content

Instantly share code, notes, and snippets.

@KooperL
Created October 13, 2023 13:05
Show Gist options
  • Save KooperL/64b2a6bc392dfa8fdb3bd933db45ea15 to your computer and use it in GitHub Desktop.
Save KooperL/64b2a6bc392dfa8fdb3bd933db45ea15 to your computer and use it in GitHub Desktop.
React centralised API state handler - reduce boilerplate code
import { useCallback, useState } from 'react'
export const fetchStatus = {
none: 0,
loading: 1,
success: 2,
error: 3,
}
export const useFetch = () => {
const [count, setCount] = useState(0)
const [state, setState] = useState({
hasResponded: false,
loading: false,
details: null,
errorMessage: null,
error: false,
success: false,
status: fetchStatus.none
})
const makeReq = useCallback(
(props) => {
setCount(count + 1)
setState({
hasResponded: false,
loading: true,
details: null,
errorMessage: null,
error: false,
success: false,
status: fetchStatus.loading
})
props
.ApiImpl({
payload: props.payload,
auth: props?.auth,
varRoute: props?.varRoute,
})
.then((resp) => {
setState({
hasResponded: true,
details: resp?.data || null,
error: false,
errorMessage: null,
loading: false,
success: true,
status: fetchStatus.success
})
props?.callback?.()
})
.catch((err) => {
setState({
hasResponded: true,
details: null,
error: true,
errorMessage: err?.message || 'Error not caught',
loading: false,
success: false,
status: fetchStatus.error
})
})
},
[state]
)
return { state, count, makeReq }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment