Skip to content

Commit

Permalink
Merge pull request #4784 from marmelab/fix-reference-input-filter-prop
Browse files Browse the repository at this point in the history
Fix ReferenceInput when using an object literal as filter prop
  • Loading branch information
fzaninotto authored May 7, 2020
2 parents 5b227f9 + 3875752 commit 626356a
Showing 1 changed file with 10 additions and 4 deletions.
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

0 comments on commit 626356a

Please sign in to comment.