import { useMemo } from 'react' ; import get from 'lodash/get' ; import { PaginationPayload , SortPayload , ReduxState , Identifier , Record , RecordMap , UseDataProviderOptions , } from '../types' ; import { useQueryWithStore , Refetch } from './useQueryWithStore' ; const defaultPagination = { page : 1 , perPage : 25 } ; const defaultSort = { field : 'id' , order : 'DESC' } ; const defaultFilter = { } ; const defaultIds = [ ] ; const defaultData = { } ; param { string } resource param { Object } pagination param { Object } sort param { Object } filter param options param { boolean } options . enabled param { Function } options . onSuccess param { Function } options . onFailure returns example const useGetList = < RecordType extends Record = Record > ( resource , pagination = defaultPagination , sort = defaultSort , filter = defaultFilter , options ? ) : { data : RecordMap < RecordType > ; ids : Identifier [ ] ; total ? : number ; error ? : any ; loading : boolean ; loaded : boolean ; refetch : Refetch ; } => { const requestSignature = JSON . stringify ( { pagination , sort , filter } ) ; const { data : { ids , allRecords } , total , error , loading , loaded , refetch , } = useQueryWithStore ( { type : 'getList' , resource , payload : { pagination , sort , filter } } , options , ( state ) : DataSelectorResult < RecordType > => ( { ids : get ( state . admin . resources , [ resource , 'list' , 'cachedRequests' , requestSignature , 'ids' ] , null ) , allRecords : get ( state . admin . resources , [ resource , 'data' ] , defaultData ) as RecordMap < RecordType > , } ) , ( state ) : number => get ( state . admin . resources , [ resource , 'list' , 'cachedRequests' , requestSignature , 'total' , ] ) , 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 === null ? defaultIds : ids , total , error , loading , loaded , refetch , } ; } ; interface DataSelectorResult < RecordType extends Record = Record > { ids : Identifier [ ] ; allRecords : RecordMap < RecordType > ; } const isDataLoaded = ( data ) => data . ids !== null ; export default useGetList ;