Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ReferenceManyField throws error after insert #5877

Merged
merged 1 commit into from
Feb 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 37 additions & 17 deletions packages/ra-core/src/dataProvider/useGetManyReference.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { useSelector, shallowEqual } from 'react-redux';
import get from 'lodash/get';
import { useMemo } from 'react';

import { CRUD_GET_MANY_REFERENCE } from '../actions/dataActions/crudGetManyReference';
import {
PaginationPayload,
Expand All @@ -8,12 +10,13 @@ import {
} from '../types';
import useQueryWithStore from './useQueryWithStore';
import {
getReferences,
getIds,
getTotal,
nameRelatedTo,
} from '../reducer/admin/references/oneToMany';
import { useMemo } from 'react';

const defaultIds = [];
const defaultData = {};

/**
* Call the dataProvider.getManyReference() method and return the resolved result
Expand Down Expand Up @@ -75,29 +78,46 @@ const useGetManyReference = (
[filter, resource, id, referencingResource, target]
);

const { data: ids, total, error, loading, loaded } = useQueryWithStore(
const {
data: { ids, allRecords },
total,
error,
loading,
loaded,
} = useQueryWithStore(
{
type: 'getManyReference',
resource: resource,
payload: { target, id, pagination, sort, filter },
},
{ ...options, relatedTo, action: CRUD_GET_MANY_REFERENCE },
selectIds(relatedTo),
selectTotal(relatedTo)
// ids and data selector
(state: ReduxState) => ({
ids: getIds(state, relatedTo) || defaultIds,
allRecords: get(
state.admin.resources,
[resource, 'data'],
defaultData
),
}),
(state: ReduxState) => getTotal(state, relatedTo)
);

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]
);
const data = useSelector(selectData(resource, relatedTo), shallowEqual);

return { data, ids, total, error, loading, loaded };
};

export default useGetManyReference;

const selectData = (reference: string, relatedTo: string) => (
state: ReduxState
) => getReferences(state, reference, relatedTo);

const selectIds = (relatedTo: string) => (state: ReduxState) =>
getIds(state, relatedTo);

const selectTotal = (relatedTo: string) => (state: ReduxState) =>
getTotal(state, relatedTo);