Skip to content

Commit

Permalink
[DataGrid] Fix header filters not displaying restored values
Browse files Browse the repository at this point in the history
  • Loading branch information
MBilalShafi committed Mar 7, 2025
1 parent 25ef40e commit 1cdd21b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
29 changes: 29 additions & 0 deletions packages/x-data-grid-pro/src/tests/filtering.DataGridPro.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,35 @@ describe('<DataGridPro /> - Filter', () => {
expect(filterCellInput).to.have.value('a');
});

// See https://github.com/mui/mui-x/issues/16826
it('should set the input state properly when using the `apiRef.current.restoreState` method', async () => {
const changeSpy = spy();
render(<TestCase headerFilters onFilterModelChange={changeSpy} />);

const filterCellInput = getColumnHeaderCell(0, 1).querySelector('input')!;
fireEvent.mouseDown(filterCellInput);
expect(filterCellInput).toHaveFocus();
fireEvent.change(filterCellInput, { target: { value: 'p' } });
clock.tick(SUBMIT_FILTER_STROKE_TIME);
expect(getColumnValues(0)).to.deep.equal(['Puma']);
expect(filterCellInput).to.have.value('p');

fireEvent.change(filterCellInput, { target: { value: '' } });
expect(filterCellInput).to.have.value('');

act(() =>
apiRef.current?.restoreState({
filter: {
filterModel: {
items: [{ field: 'brand', operator: 'contains', value: 'b' }],
},
},
}),
);

expect(filterCellInput).to.have.value('b');
});

it('should apply filters on type when the focus is on cell', () => {
render(<TestCase headerFilters />);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ function GridFilterInputValue(props: GridTypeFilterInputValueProps) {
const [filterValueState, setFilterValueState] = React.useState<string | undefined>(
sanitizeFilterItemValue(item.value),
);
const lastValue = React.useRef<string | undefined>(filterValueState);
const [applying, setIsApplying] = React.useState(false);
const id = useId();
const rootProps = useGridRootProps();
Expand All @@ -59,8 +60,14 @@ function GridFilterInputValue(props: GridTypeFilterInputValueProps) {

React.useEffect(() => {
const itemPlusTag = item as ItemPlusTag;
if (itemPlusTag.fromInput !== id || item.value == null) {
setFilterValueState(sanitizeFilterItemValue(item.value));
const sanitizedValue = sanitizeFilterItemValue(item.value);
if (
itemPlusTag.fromInput !== id ||
item.value == null ||
sanitizedValue !== lastValue.current
) {
setFilterValueState(sanitizedValue);
lastValue.current = sanitizedValue;
}
}, [id, item]);

Expand Down

0 comments on commit 1cdd21b

Please sign in to comment.