1
- import { useSelector , shallowEqual } from 'react-redux ' ;
1
+ import { useMemo } from 'react' ;
2
2
import get from 'lodash/get' ;
3
3
4
4
import {
@@ -11,6 +11,7 @@ import {
11
11
} from '../types' ;
12
12
import useQueryWithStore from './useQueryWithStore' ;
13
13
14
+ const defaultIds = [ ] ;
14
15
const defaultData = { } ;
15
16
16
17
/**
@@ -67,16 +68,28 @@ const useGetList = <RecordType extends Record = Record>(
67
68
} => {
68
69
const requestSignature = JSON . stringify ( { pagination, sort, filter } ) ;
69
70
70
- const { data : ids , total, error, loading, loaded } = useQueryWithStore (
71
+ const {
72
+ data : { ids, allRecords } ,
73
+ total,
74
+ error,
75
+ loading,
76
+ loaded,
77
+ } = useQueryWithStore (
71
78
{ type : 'getList' , resource, payload : { pagination, sort, filter } } ,
72
79
options ,
73
- // data selector (may return [])
74
- ( state : ReduxState ) : Identifier [ ] =>
75
- get (
80
+ // ids and data selector
81
+ ( state : ReduxState ) : DataSelectorResult < RecordType > => ( {
82
+ ids : get (
76
83
state . admin . resources ,
77
84
[ resource , 'list' , 'cachedRequests' , requestSignature , 'ids' ] ,
78
- [ ]
85
+ null
79
86
) ,
87
+ allRecords : get (
88
+ state . admin . resources ,
89
+ [ resource , 'data' ] ,
90
+ defaultData
91
+ ) ,
92
+ } ) ,
80
93
// total selector (may return undefined)
81
94
( state : ReduxState ) : number =>
82
95
get ( state . admin . resources , [
@@ -85,26 +98,37 @@ const useGetList = <RecordType extends Record = Record>(
85
98
'cachedRequests' ,
86
99
requestSignature ,
87
100
'total' ,
88
- ] )
101
+ ] ) ,
102
+ ( data : DataSelectorResult < RecordType > ) => data . ids !== null
89
103
) ;
90
104
91
- const data = useSelector ( ( state : ReduxState ) : RecordMap < RecordType > => {
92
- if ( ! ids ) return defaultData ;
93
- const allResourceData = get (
94
- state . admin . resources ,
95
- [ resource , 'data' ] ,
96
- defaultData
97
- ) ;
98
- return ids
99
- . map ( id => allResourceData [ id ] )
100
- . reduce ( ( acc , record ) => {
101
- if ( ! record ) return acc ;
102
- acc [ record . id ] = record ;
103
- return acc ;
104
- } , { } ) ;
105
- } , shallowEqual ) ;
105
+ const data = useMemo (
106
+ ( ) =>
107
+ ids === null
108
+ ? defaultData
109
+ : ids
110
+ . map ( id => allRecords [ id ] )
111
+ . reduce ( ( acc , record ) => {
112
+ if ( ! record ) return acc ;
113
+ acc [ record . id ] = record ;
114
+ return acc ;
115
+ } , { } ) ,
116
+ [ ids , allRecords ]
117
+ ) ;
106
118
107
- return { data, ids, total, error, loading, loaded } ;
119
+ return {
120
+ data,
121
+ ids : ids === null ? defaultIds : ids ,
122
+ total,
123
+ error,
124
+ loading,
125
+ loaded,
126
+ } ;
108
127
} ;
109
128
129
+ interface DataSelectorResult < RecordType extends Record = Record > {
130
+ ids : Identifier [ ] ;
131
+ allRecords : RecordMap < RecordType > ;
132
+ }
133
+
110
134
export default useGetList ;
0 commit comments