Skip to content

Instantly share code, notes, and snippets.

@yilmazcakmakci
Created August 9, 2021 09:55
Show Gist options
  • Select an option

  • Save yilmazcakmakci/df632767117c2d4e23f6b55a442dda81 to your computer and use it in GitHub Desktop.

Select an option

Save yilmazcakmakci/df632767117c2d4e23f6b55a442dda81 to your computer and use it in GitHub Desktop.
A React hook for handle different states on async requests without useState in component.
import { useEffect, useState, useCallback } from 'react'
const useFetch = (fetcher, { params = {}, immediate = false } = {}) => {
const [loading, setLoading] = useState(false)
const [data, setValue] = useState(null)
const [error, setError] = useState(null)
const execute = useCallback(
(executeParams) => {
setLoading(true)
setValue(null)
setError(null)
return fetcher(executeParams ? executeParams : params)
.then((response) => {
setValue(response)
})
.catch((error) => {
setError(error)
})
.finally(() => {
setLoading(false)
})
},
[fetcher]
)
useEffect(() => {
if (immediate) {
execute()
}
}, [execute, immediate])
return [loading, data, error, execute]
}
export default useFetch
/*
Usage
const [loading, todos, error, fetchTodos] = useFetch(_getTodos, {
params: { id: 2 },
immediate: true,
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment