import { useMemo , useRef } from 'react' ; import get from 'lodash/get' ; import { PaginationPayload , SortPayload , ReduxState , Identifier , Record , RecordMap , } from '../types' ; import { useQueryWithStore , Refetch } from './useQueryWithStore' ; const defaultIds = [ ] ; const defaultData = { } ; param { string } resource param { Object } pagination param { Object } sort param { Object } filter param { Object } options returns example export const useGetMainList = < RecordType extends Record = Record > ( resource , pagination , sort , filter , options ? ) : { data ? : RecordMap < RecordType > ; ids ? : Identifier [ ] ; total ? : number ; error ? : any ; loading : boolean ; loaded : boolean ; refetch : Refetch ; } => { const requestSignature = JSON . stringify ( { pagination , sort , filter } ) ; const memo = useRef < Memo < RecordType > > ( { } ) ; const { data : { finalIds , finalTotal , allRecords } , error , loading , loaded , refetch , } = useQueryWithStore ( { type : 'getList' , resource , payload : { pagination , sort , filter } } , options , ( state ) : DataSelectorResult < RecordType > => { const ids = get ( state . admin . resources , [ resource , 'list' , 'cachedRequests' , requestSignature , 'ids' , ] ) ; const total = get ( state . admin . resources , [ resource , 'list' , 'cachedRequests' , requestSignature , 'total' , ] ) ; const mainIds = get ( state . admin . resources , [ resource , 'list' , 'ids' , ] ) ; const mainTotal = get ( state . admin . resources , [ resource , 'list' , 'total' , ] ) ; const finalIds = typeof ids === 'undefined' ? mainIds : ids ; const finalTotal = typeof total === 'undefined' ? mainTotal : total ; const allRecords = get ( state . admin . resources , [ resource , 'data' ] , defaultData ) as RecordMap < RecordType > ; if ( memo . current . finalIds !== finalIds || memo . current . finalTotal !== finalTotal || memo . current . allRecords !== allRecords ) { const result = { finalIds , finalTotal , allRecords , } ; memo . current = { finalIds , finalTotal , allRecords , result } ; } return memo . current . result ; } , ( ) => null , isDataLoaded ) ; const data = useMemo ( ( ) => typeof finalIds === 'undefined' ? defaultData : finalIds . map ( id => allRecords [ id ] ) . reduce ( ( acc , record ) => { if ( ! record ) return acc ; acc [ record . id ] = record ; return acc ; } , { } ) , [ finalIds , allRecords ] ) ; return { data , ids : typeof finalIds === 'undefined' ? defaultIds : finalIds , total : finalTotal , error , loading , loaded , refetch , } ; } ; interface DataSelectorResult < RecordType extends Record = Record > { finalIds ? : Identifier [ ] ; finalTotal : number ; allRecords : RecordMap < RecordType > ; } interface Memo < RecordType extends Record = Record > { finalIds ? : Identifier [ ] ; finalTotal ? : number ; allRecords ? : RecordMap < RecordType > ; result ? : DataSelectorResult < RecordType > ; } const isDataLoaded = ( data ) => data . finalTotal != null ;