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 ReferenceInput when using an object literal as filter prop #4784

Merged
merged 1 commit into from
May 7, 2020
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
14 changes: 10 additions & 4 deletions packages/ra-core/src/controller/useFilterState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ interface UseFilterStateProps {
}

const defaultFilterToQuery = (v: string) => ({ q: v });
const emptyFilter = {};

/**
* Hooks to provide filter state and setFilter which update the query part of the filter
Expand Down Expand Up @@ -53,7 +52,7 @@ const emptyFilter = {};
*/
export default ({
filterToQuery = defaultFilterToQuery,
permanentFilter = emptyFilter,
permanentFilter = {},
debounceTime = 500,
}: UseFilterStateOptions): UseFilterStateProps => {
const permanentFilterProp = useRef(permanentFilter);
Expand All @@ -62,6 +61,13 @@ export default ({
...permanentFilter,
...filterToQuery(''),
});
// Developers often pass an object literal as permanent filter
// e.g. <ReferenceInput source="book_id" reference="books" filter={{ is_published: true }}>
// The effect should execute again when the parent component updates the filter value,
// but not when the object literal describes the same values. Therefore,
// we use JSON.stringify(permanentFilter) in the `useEffect` and `useCallback`
// dependencies instead of permanentFilter.
const permanentFilterSignature = JSON.stringify(permanentFilter);

useEffect(() => {
if (!isEqual(permanentFilterProp.current, permanentFilter)) {
Expand All @@ -71,7 +77,7 @@ export default ({
...filterToQuery(latestValue.current),
});
}
}, [permanentFilter, permanentFilterProp, filterToQuery]);
}, [permanentFilterSignature, permanentFilterProp, filterToQuery]); // eslint-disable-line react-hooks/exhaustive-deps

const setFilter = useCallback(
debounce((value: string) => {
Expand All @@ -81,7 +87,7 @@ export default ({
});
latestValue.current = value;
}, debounceTime),
[permanentFilter]
[permanentFilterSignature] // eslint-disable-line react-hooks/exhaustive-deps
);

return {
Expand Down