Skip to content

Instantly share code, notes, and snippets.

@AkshatGiri
Created May 16, 2022 21:16
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 AkshatGiri/c54dda4f0cbd998f70e959ddeace06b9 to your computer and use it in GitHub Desktop.
Save AkshatGiri/c54dda4f0cbd998f70e959ddeace06b9 to your computer and use it in GitHub Desktop.
import { useState } from 'react'
// These api states should be imported into whichever component uses this hook
// and should use ApiStates.{state} to do comparisons and not do direct string comparisons.
export const ApiStates = {
IDLE: 'IDLE',
LOADING: 'LOADING',
ERROR: 'ERROR',
SUCCESS: 'SUCCESS',
}
const initErrorInfo = {
status: 0,
message: '',
}
/**
*
* @param {async function} apiCallFunc
* @param {object that needs to be passed to the apiCallFunc async function} args
* @returns
*
* This hook can be used with an async function so that it keeps track of the api state
* Look at ApiStates for the availble states. This allows us to manage api states in a
* way that acts like state machines. This will make component logic easier to read and
* make api calls with.
*
* Future Improvement: Allow dev to pass in object containing possible error code and
* callback functions that fire when we run into that error.
*/
function useApiStateManager(apiCallFunc) {
const [apiState, setApiState] = useState(ApiStates.IDLE)
const [errorInfo, setErrorInfo] = useState(initErrorInfo)
const [responseData, setResponseData] = useState()
const makeRequest = async (args) => {
try {
setApiState(ApiStates.LOADING)
const response = await apiCallFunc(args)
setResponseData(response)
setApiState(ApiStates.SUCCESS)
return response
} catch (error) {
setErrorInfo(error)
setApiState(ApiStates.ERROR)
}
}
return [makeRequest, apiState, responseData, errorInfo]
}
export default useApiStateManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment