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 filters not matching inputs are ignored without syncWithLocation #9283

Merged
merged 2 commits into from
Sep 15, 2023
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
20 changes: 13 additions & 7 deletions packages/ra-ui-materialui/src/list/filter/FilterForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,26 @@ export const FilterForm = (props: FilterFormProps) => {
const form = useForm({
defaultValues: mergedInitialValuesWithDefaultValues,
});
const { getValues, reset, trigger, watch } = form;

// Reapply filterValues when the URL changes or a user removes a filter
useEffect(() => {
const newValues = getFilterFormValues(form.getValues(), filterValues);
if (!isEqual(newValues, form.getValues())) {
form.reset(newValues);
const newValues = getFilterFormValues(getValues(), filterValues);
if (!isEqual(newValues, getValues())) {
reset(newValues);
}
}, [filterValues, form]);
// The reference to the filterValues object is not updated when it changes,
// so we must stringify it to compare it by value and also compare the reference.
// This makes it work for both input values and filters applied directly through
// the ListContext.setFilter (e.g. QuickFilter in the simple example)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(filterValues), filterValues, getValues, reset]);

useEffect(() => {
const subscription = form.watch(async (values, { name }) => {
const subscription = watch(async (values, { name }) => {
// We must check whether the form is valid as watch will not check that for us.
// We can't rely on form state as it might not be synchronized yet
const isFormValid = await form.trigger();
const isFormValid = await trigger();

if (isFormValid) {
if (get(values, name) === '') {
Expand All @@ -71,7 +77,7 @@ export const FilterForm = (props: FilterFormProps) => {
}
});
return () => subscription.unsubscribe();
}, [displayedFilters, form, setFilters]);
}, [displayedFilters, setFilters, trigger, watch]);

return (
<FormProvider {...form}>
Expand Down
Loading