import get from 'lodash/get' ; import { useMemo } from 'react' ; import { CRUD_GET_MANY_REFERENCE } from '../actions/dataActions/crudGetManyReference' ; import { PaginationPayload , SortPayload , Identifier , ReduxState , Record , RecordMap , } from '../types' ; import { useQueryWithStore } from './useQueryWithStore' ; import { getIds , getTotal , nameRelatedTo , } from '../reducer/admin/references/oneToMany' ; const defaultIds = [ ] ; const defaultData = { } ; interface UseGetManyReferenceOptions { onSuccess ? : ( args ? : any ) => void ; onFailure ? : ( error : any ) => void ; enabled ? : boolean ; [ key ] : any ; } param { string } resource param { string } target param { Object } id param { Object } pagination param { Object } sort param { Object } filter param { string } referencingResource param options param { boolean } options . enabled param { Function } options . onSuccess param { Function } options . onFailure returns example const useGetManyReference = ( resource , target , id , pagination , sort , filter , referencingResource , options ? ) => { const relatedTo = useMemo ( ( ) => nameRelatedTo ( resource , id , referencingResource , target , filter ) , [ filter , resource , id , referencingResource , target ] ) ; const { data : { ids , allRecords } , total , error , loading , loaded , refetch , } = useQueryWithStore ( { type : 'getManyReference' , resource : resource , payload : { target , id , pagination , sort , filter } , } , { ... options , relatedTo , action : CRUD_GET_MANY_REFERENCE } , ( state ) => ( { ids : getIds ( state , relatedTo ) , allRecords : get ( state . admin . resources , [ resource , 'data' ] , defaultData ) , } ) , ( state ) => getTotal ( state , relatedTo ) , isDataLoaded ) ; const data = useMemo ( ( ) => ids == null ? defaultData : ids . map ( id => allRecords [ id ] ) . reduce ( ( acc , record ) => { if ( ! record ) return acc ; acc [ record . id ] = record ; return acc ; } , { } ) , [ ids , allRecords ] ) ; return { data , ids : ids || defaultIds , total , error , loading , loaded , refetch , } ; } ; interface DataSelectorResult < RecordType extends Record = Record > { ids : Identifier [ ] ; allRecords : RecordMap < RecordType > ; } const isDataLoaded = ( data ) => data . ids != null ; export default useGetManyReference ;