TanStackT
TanStack3y ago
1 reply
dangerous-fuchsia

global filter function that accesses outside state

I want to filter my rows based on their edited state. I already maintain the row state so I can render 'modified' rows differently, and it works great. But in order to filter on the state, I tried to do this:

const [stateFilter, setStateFilter] = useState<string|undefined>();

const globalFilterWithState = (row: Row<TData>, columnId: string, filterValue: string): boolean => {
    const text = `${row.getValue(columnId)}`.toLowerCase();
    const includesText = text.includes(filterValue.toLowerCase());

    if (includesText && stateFilter) {
      const state = editableState.itemState(row.original);
      return stateFilter === state;
    }
    return includesText;
};

const tableInstance = useReactTable({
    ...
    globalFilterFn: globalFilterWithState,
    ...
});


Then in my filtering component I call tableInstance.setGlobalFilter("search text") and it works great. The problem is that when I call setStateFilter("Modified") the filtering does not work until tableInstance.setGlobalFilter("search text") is called with a new value.

By calling setStateFilter I am essentially changing the value of what is passed to globalFilterFn, but it seems that does not cause the filter to be run.

The only other option I can think of would be to make a fake (hidden) state column, and try to implement this as a column filter.

Any thoughts?
Was this page helpful?