import { useSelector } from 'react-redux' ; import get from 'lodash/get' ; import { CRUD_GET_MATCHING } from '../actions/dataActions/crudGetMatching' ; import { Identifier , PaginationPayload , SortPayload , Record , ReduxState , } from '../types' ; import { useQueryWithStore , Refetch } from './useQueryWithStore' ; import { getReferenceResource , getPossibleReferenceValues , getPossibleReferences , } from '../reducer' ; interface UseGetMatchingOptions { onSuccess ? : ( args ? : any ) => void ; onFailure ? : ( error : any ) => void ; enabled ? : boolean ; [ key ] : any ; } const referenceSource = ( resource , source ) => `${ resource }@${ source }` ; param { string } resource param { Object } pagination param { Object } sort param { Object } filter param { string } source param { string } referencingResource param options param { boolean } options . enabled param { Function } options . onSuccess param { Function } options . onFailure returns example const useGetMatching = ( resource , pagination , sort , filter , source , referencingResource , options ? ) : UseGetMatchingResult => { const relatedTo = referenceSource ( referencingResource , source ) ; const payload = { pagination , sort , filter } ; const { data : possibleValues , total , error , loading , loaded , refetch , } = useQueryWithStore ( { type : 'getList' , resource , payload , } , { ... options , relatedTo , action : CRUD_GET_MATCHING , } , ( state ) => getPossibleReferenceValues ( state , { referenceSource , resource : referencingResource , source , } ) , ( state ) => get ( state . admin . resources , [ resource , 'list' , 'cachedRequests' , JSON . stringify ( payload ) , 'total' , ] , null ) ) ; const referenceState = useSelector ( state => getReferenceResource ( state , { reference : resource , } ) ) ; const possibleReferences = getPossibleReferences ( referenceState , possibleValues , [ ] ) ; return { data : possibleReferences , ids : possibleValues , total , error , loading , loaded , refetch , } ; } ; interface UseGetMatchingResult { data : Record [ ] ; ids : Identifier [ ] ; total : number ; error ? : any ; loading : boolean ; loaded : boolean ; refetch : Refetch ; } export default useGetMatching ;