import { useCallback , useEffect , useState } from 'react' ; import { useSafeSetState } from '../util/hooks' ; import { OnSuccess , OnFailure } from '../types' ; import useDataProvider from './useDataProvider' ; import useDataProviderWithDeclarativeSideEffects from './useDataProviderWithDeclarativeSideEffects' ; import { DeclarativeSideEffect } from './useDeclarativeSideEffects' ; import useVersion from '../controller/useVersion' ; import { DataProviderQuery , Refetch } from './useQueryWithStore' ; param query param { string } query . type param { string } query . resource param { Object } query . payload param options param { string } options . action param { boolean } options . enabled param { Function } options . onSuccess param { Function } options . onFailure param { boolean } options . withDeclarativeSideEffectsSupport returns example example export const useQuery = ( query , options = { onSuccess : undefined } ) : UseQueryValue => { const { type , resource , payload } = query ; const { withDeclarativeSideEffectsSupport , ... otherOptions } = options ; const version = useVersion ( ) ; const [ innerVersion , setInnerVersion ] = useState ( 0 ) ; const refetch = useCallback ( ( ) => { setInnerVersion ( prevInnerVersion => prevInnerVersion + 1 ) ; } , [ ] ) ; const requestSignature = JSON . stringify ( { query , options : otherOptions , version , innerVersion , } ) ; const [ state , setState ] = useSafeSetState < UseQueryValue > ( { data : undefined , error : null , total : null , loading : true , loaded : false , refetch , } ) ; const dataProvider = useDataProvider ( ) ; const dataProviderWithDeclarativeSideEffects = useDataProviderWithDeclarativeSideEffects ( ) ; useEffect ( ( ) => { deprecated const finalDataProvider = withDeclarativeSideEffectsSupport ? dataProviderWithDeclarativeSideEffects : dataProvider ; setState ( prevState => ( { ... prevState , loading : true } ) ) ; finalDataProvider [ type ] . apply ( finalDataProvider , typeof resource !== 'undefined' ? [ resource , payload , otherOptions ] : [ payload , otherOptions ] ) . then ( ( { data , total } ) => { setState ( { data , total , loading : false , loaded : true , refetch , } ) ; } ) . catch ( error => { setState ( { error , loading : false , loaded : false , refetch , } ) ; } ) ; } , [ requestSignature , dataProvider , dataProviderWithDeclarativeSideEffects , setState , ] ) ; return state ; } ; export interface UseQueryOptions { action ? : string ; enabled ? : boolean ; onSuccess ? : OnSuccess | DeclarativeSideEffect ; onFailure ? : OnFailure | DeclarativeSideEffect ; withDeclarativeSideEffectsSupport ? : boolean ; } export type UseQueryValue = { data ? : any ; total ? : number ; error ? : any ; loading : boolean ; loaded : boolean ; refetch : Refetch ; } ;