import { useEffect } from 'react' ; import { useImmer } from 'use-immer' ; interface Store { loading : boolean ; res : any ; err : any ; } interface Options { loading : boolean ; setLoading : ( loading : boolean ) => void ; err : any ; refresh : ( ... args : any ) => void ; } param request param initialValue param args export default function useAwait < T > ( request , initialValue ? , ... args ) { const [ store , setStore ] = useImmer < Store > ( { loading : true , res : initialValue , err : null } ) ; const { loading , res , err } = store ; useEffect ( ( ) => { loading && getData ( args ) ; } , [ loading , args ] ) ; function getData ( args ) { const response = request ( ... args ) ; response . then ( res => { setStore ( store => { store . res = res ; store . loading = false ; store . err = null ; } ) ; } ) . catch ( e => { setStore ( store => { store . loading = false ; store . err = e ; } ) ; } ) ; } function refresh ( ... args ) { getData ( args ) ; } function setLoading ( loading ) { setStore ( store => { store . loading = loading ; } ) ; } return [ res , { loading , setLoading , err , refresh } , ] ; }