Skip to content

Instantly share code, notes, and snippets.

@fResult
Created October 3, 2020 11:57
Show Gist options
  • Save fResult/c02781f5465132d506cd79678d584429 to your computer and use it in GitHub Desktop.
Save fResult/c02781f5465132d506cd79678d584429 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useCallback } from 'react'
export default (asyncFunction, immediate = true) => {
const [isLoading, setIsLoading] = useState(false)
const [value, setValue] = useState(null)
const [error, setError] = useState(null)
const execute = useCallback(
async (params = {}, config = {}) => {
setIsLoading(true)
setValue(null)
setError(null)
console.log('useAsync: BEFORE REQUEST: UPLOAD')
try {
const res = await asyncFunction(params, config)
console.log('useAsync: RESPONSE SUCCESS:', res)
setValue(res?.data)
} catch (err) {
console.error('useAsync: RESPONSE ERROR:', JSON.stringify(err), err)
setError(err)
} finally {
console.log('useAsync: FINALLY: UPLOAD')
setIsLoading(false)
}
},
[asyncFunction]
)
useEffect(() => {
if (immediate) {
execute()
}
}, [execute, immediate])
return { execute, isLoading, value, error }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment