Skip to content

Commit

Permalink
Merge pull request #7952 from marmelab/strict-null-checks
Browse files Browse the repository at this point in the history
[TypeScript] Fix some strict null checks in ra-core
  • Loading branch information
djhi committed Jul 8, 2022
2 parents 84306af + 156eeb1 commit ea8c82d
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ describe('useReferenceManyFieldController', () => {
source="items"
reference="bar"
target="foo_id"
record={{ id: 1, items: [1, 2] }}
>
{props => <ComponentToTest {...props} />}
</ReferenceManyFieldController>
Expand Down Expand Up @@ -66,6 +67,7 @@ describe('useReferenceManyFieldController', () => {
source="items"
reference="bar"
target="foo_id"
record={{ id: 1, items: [1, 2] }}
>
{props => <ComponentToTest {...props} />}
</ReferenceManyFieldController>
Expand Down
59 changes: 33 additions & 26 deletions packages/ra-core/src/controller/list/useList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,21 @@ export const useList = <RecordType extends RaRecord = any>(
isLoading = false,
page: initialPage = 1,
perPage: initialPerPage = 1000,
sort: initialSort = defaultSort,
sort: initialSort,
} = props;
const resource = useResourceContext(props);

const [fetchingState, setFetchingState] = useSafeSetState<boolean>(
isFetching
);
const [loadingState, setLoadingState] = useSafeSetState<boolean>(isLoading);
) as [boolean, (isFetching: boolean) => void];

const [loadingState, setLoadingState] = useSafeSetState<boolean>(
isLoading
) as [boolean, (isFetching: boolean) => void];

const [finalItems, setFinalItems] = useSafeSetState<{
data?: RecordType[];
total: number;
total?: number;
}>(() => ({
data,
total: data ? data.length : undefined,
Expand Down Expand Up @@ -154,26 +157,28 @@ export const useList = <RecordType extends RaRecord = any>(
useEffect(
() => {
if (isLoading || !data) return;
let tempData = data;

// 1. filter
let tempData = data.filter(record =>
Object.entries(filterValues).every(
([filterName, filterValue]) => {
const recordValue = get(record, filterName);
const result = Array.isArray(recordValue)
? Array.isArray(filterValue)
? recordValue.some(item =>
filterValue.includes(item)
)
: recordValue.includes(filterValue)
: Array.isArray(filterValue)
? filterValue.includes(recordValue)
: filterValue == recordValue; // eslint-disable-line eqeqeq
return result;
}
)
);

if (filterValues) {
tempData = data.filter(record =>
Object.entries(filterValues).every(
([filterName, filterValue]) => {
const recordValue = get(record, filterName);
const result = Array.isArray(recordValue)
? Array.isArray(filterValue)
? recordValue.some(item =>
filterValue.includes(item)
)
: recordValue.includes(filterValue)
: Array.isArray(filterValue)
? filterValue.includes(recordValue)
: filterValue == recordValue; // eslint-disable-line eqeqeq
return result;
}
)
);
}
const filteredLength = tempData.length;

// 2. sort
Expand Down Expand Up @@ -224,12 +229,15 @@ export const useList = <RecordType extends RaRecord = any>(

return {
sort,
data: finalItems.data,
data: finalItems?.data,
defaultTitle: '',
error,
displayedFilters,
filterValues,
hasNextPage: page * perPage < finalItems.total,
hasNextPage:
finalItems?.total == null
? false
: page * perPage < finalItems.total,
hasPreviousPage: page > 1,
hideFilter,
isFetching: fetchingState,
Expand All @@ -247,7 +255,7 @@ export const useList = <RecordType extends RaRecord = any>(
setPerPage,
setSort,
showFilter,
total: finalItems.total,
total: finalItems?.total,
};
};

Expand All @@ -268,4 +276,3 @@ export type UseListValue<
> = ListControllerResult<RecordType>;

const defaultFilter = {};
const defaultSort = { field: null, order: null };
2 changes: 1 addition & 1 deletion packages/ra-core/src/controller/list/useListController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const useListController = <RecordType extends RaRecord = any>(
useEffect(() => {
if (
query.page <= 0 ||
(!isFetching && query.page > 1 && data.length === 0)
(!isFetching && query.page > 1 && data?.length === 0)
) {
// Query for a page that doesn't exist, set page to 1
queryModifiers.setPage(1);
Expand Down
31 changes: 21 additions & 10 deletions packages/ra-core/src/dataProvider/useGetMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,14 @@ export const useGetMany = <RecordType extends RaRecord = any>(
const queryCache = queryClient.getQueryCache();

return useQuery<RecordType[], Error, RecordType[]>(
[resource, 'getMany', { ids: ids.map(id => String(id)), meta }],
[
resource,
'getMany',
{
ids: !ids || ids.length === 0 ? [] : ids.map(id => String(id)),
meta,
},
],
() => {
if (!ids || ids.length === 0) {
// no need to call the dataProvider
Expand All @@ -72,18 +79,22 @@ export const useGetMany = <RecordType extends RaRecord = any>(
},
{
placeholderData: () => {
const records = ids.map(id => {
const queryHash = hashQueryKey([
resource,
'getOne',
{ id: String(id), meta },
]);
return queryCache.get<RecordType>(queryHash)?.state?.data;
});
const records =
!ids || ids.length === 0
? []
: ids.map(id => {
const queryHash = hashQueryKey([
resource,
'getOne',
{ id: String(id), meta },
]);
return queryCache.get<RecordType>(queryHash)
?.state?.data;
});
if (records.some(record => record === undefined)) {
return undefined;
} else {
return records;
return records as RecordType[];
}
},
onSuccess: data => {
Expand Down
8 changes: 4 additions & 4 deletions packages/ra-core/src/dataProvider/useGetManyAggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const useGetManyAggregate = <RecordType extends RaRecord = any>(
if (records.some(record => record === undefined)) {
return undefined;
} else {
return records;
return records as RecordType[];
}
}, [ids, queryCache, resource, meta]);

Expand Down Expand Up @@ -138,9 +138,9 @@ export const useGetManyAggregate = <RecordType extends RaRecord = any>(
* // and sum will be equal to 10
*/
const batch = fn => {
let capturedArgs = [];
let timeout = null;
return arg => {
let capturedArgs: any[] = [];
let timeout: ReturnType<typeof setTimeout> | null = null;
return (arg: any) => {
capturedArgs.push(arg);
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
Expand Down
11 changes: 8 additions & 3 deletions packages/ra-core/src/dataProvider/useGetManyReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,12 @@ export const useGetManyReference = <RecordType extends RaRecord = any>(
'getManyReference',
{ target, id, pagination, sort, filter, meta },
],
() =>
dataProvider
() => {
if (!target || id == null) {
// check at runtime to support partial parameters with the enabled option
return Promise.reject(new Error('target and id are required'));
}
return dataProvider
.getManyReference<RecordType>(resource, {
target,
id,
Expand All @@ -97,7 +101,8 @@ export const useGetManyReference = <RecordType extends RaRecord = any>(
data,
total,
pageInfo,
})),
}));
},
{
onSuccess: ({ data }) => {
// optimistically populate the getOne cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('<ReferenceManyField />', () => {
page: 1,
perPage: 10,
target: 'post_id',
record: { id: 1 },
};

it('should render a list of the child component', async () => {
Expand Down

0 comments on commit ea8c82d

Please sign in to comment.