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

Wrong type for GlobalFilterTableState #5908

Open
2 tasks done
JoachimKoenigslieb opened this issue Feb 6, 2025 · 1 comment
Open
2 tasks done

Wrong type for GlobalFilterTableState #5908

JoachimKoenigslieb opened this issue Feb 6, 2025 · 1 comment

Comments

@JoachimKoenigslieb
Copy link

JoachimKoenigslieb commented Feb 6, 2025

TanStack Table version

8.20.5

Framework/Library version

Svelte 5.0.0

Describe the bug and the steps to reproduce it

Hi guys,

I think there some issues with the

export interface GlobalFilterTableState {
   globalFilter: any;
}

Definitions. When used with TableState this any is poisoning everything. It turns out that run-time behaviour expects that the tableState look something like:

// createSvelteTable calls createTable. This is shadcn writing an adapter.
	const table = createSvelteTable({
                ...otherProps,
		state: {
			get globalFilter() {
                                // this should return a string to filter on! But since TableState extends from (among others) GlobalFilterTableState the return value can be `any`.  
				return globalFilter.globalFilter;
			}
		},
	});

This was a pretty big problem as I thought I could just return something shaped like a GlobalFilterTableState:

	let myGlobalFilterState= $derived.by(() => {
		return { globalFilter: params.q } satisfies GlobalFilterTableState; // THIS IS A TYPE ERROR IN THE LIB... I SPENT 1 HOUR FINDING THIS....
	});

	const table = createSvelteTable({
                ...otherProps,
		state: {
			get globalFilter() {
                                // this should return a string to filter on! But since TableState extends from (among others) GlobalFilterTableState the return value can be `any`.  
				return myGlobalFilterState; // this passes typescript but gives unexpected results at runtime! It should be a string here!
			}
		},
	});

Your Minimal, Reproducible Example - (Sandbox Highly Recommended)

https://www.typescriptlang.org/play/?#code/JASwtgDg9gTgLgAgN4ChjDgTwgUwQYSgBsBXMAOwBEcAzAGjWAHMc5CYcAlKAdwFkoAExxEG6FnABiIInBwdB3fkJFjmrAMqw5i3gOGjGWXAgDiRKACMAhkWmz5AFWuWiODXGtyxAXwQ0YKDAEACIAAU9yAGdPAGM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+RAS60Dz3QYv7+n+v5Ljr0vOdf8RdP8Zc5dd4gA

Screenshots or Videos (Optional)

No response

Do you intend to try to help solve this bug with your own PR?

None

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
@fblettner
Copy link

Hello,
I don't know exactly for svelte but for React, to solve this, i have added a feature for global filter. It is a workaround but with this i was able to solve Typescript error and runtime error

import { ITableRow, TablesGridHardCoded } from '@ly_types/lyTables';
import {
    functionalUpdate,
    InitialTableState,
    makeStateUpdater,
    OnChangeFn,
    RowData,
    Table,
    Updater,
} from '@tanstack/react-table';

// Define the custom feature's state
export interface GlobalFilterState {
    globalFilter: string
}

// Define the custom feature's options
export interface GlobalFilterOptions {
    onGlobalFilterChange?: OnChangeFn<GlobalFilterState['globalFilter']>;

}

// Define the custom feature's instance methods
export interface GlobalFilterInstance {   
    clearGlobalFilter: () => void
    applyGlobalFilter: (filter: string, rows: ITableRow[]) => ITableRow[]
}

// Use declaration merging to extend TanStack Table's types
declare module '@tanstack/react-table' {
    interface TableState extends GlobalFilterState { }
    interface TableOptionsResolved<TData extends RowData>
        extends GlobalFilterOptions { }
    interface Table<TData extends RowData> extends GlobalFilterInstance { }
}

// Define the feature
export const GlobalFilterFeature = {
    getInitialState: (initialState?: InitialTableState): GlobalFilterState => ({
        globalFilter: '',
        ...initialState,
    }),

    getDefaultOptions: <TData extends ITableRow>(
        table: Table<TData>
    ): GlobalFilterOptions => ({
        onGlobalFilterChange: makeStateUpdater('globalFilter', table),
    }),

    createTable: <TData extends ITableRow>(table: Table<TData>) => {
        // Set the global filter
        table.setGlobalFilter = (updater: Updater<string>) => {
            const safeUpdater = functionalUpdate(updater, table.getState().globalFilter);
            table.options.onGlobalFilterChange?.(safeUpdater);
        };

        // Clear the global filter
        table.clearGlobalFilter = () => {
            table.setGlobalFilter(''); // Reset filter to empty string
        };

        // Method to filter rows based on the current global filter value
        table.applyGlobalFilter = (filter: string, rows: ITableRow[]) => {
            if (!filter) return rows; // Return all rows if no filter value

            return rows.filter((row: RowData) => {
                return Object.keys(row as ITableRow).some((columnId) => {
                    if (columnId === TablesGridHardCoded.row_id) return false; 

                    const value = (row as ITableRow)[columnId];
                    const safeValue = (() => {
                        if (value === null || value === undefined) {
                            return ''; // Treat null/undefined as empty strings
                        }
                        if (typeof value === 'number') {
                            return String(value); // Convert numbers to strings
                        }
                        if (typeof value === 'boolean') {
                            return value ? 'true' : 'false'; // Convert boolean to 'true'/'false'
                        }
                        return String(value); // Convert other types to strings
                    })();
                    return safeValue.toLowerCase().includes(filter.toLowerCase());
                });
            });
        };

    },
};

And declare this feature when creating the table

    const table = useReactTable({
        _features: [DensityFeature, RowSelectionFeature, TableEditFeature, ClipboardFeature, GlobalFilterFeature],
        data: tableState.filteredRows,
        columns: tableState.tableData.columns,
        getFilteredRowModel: getFilteredRowModel(),
        state: {
            sorting: tableState.sorting,
            density: tableState.density,
            columnVisibility: tableState.tableData.columnsVisibility,
            rowSelection: tableState.selectedRowModel,
            tableEdit: tableState.tableEdit,
            clipboard: tableState.clipboard,
            globalFilter: tableState.globalFilter,
            columnFilters
        },
        onGlobalFilterChange: (updaterOrValue) => {
            setTableState((prevState) => {
                const newGlobalFilter = typeof updaterOrValue === 'function'
                    ? updaterOrValue(prevState.globalFilter)
                    : updaterOrValue;

                const filteredRows = table.applyGlobalFilter(newGlobalFilter, tableState.tableData.rows);
                return {
                    ...prevState,
                    globalFilter: newGlobalFilter,  // Update global filter
                    filteredRows,  // Update the filtered rows based on the new global filter
                };
            });
        },        
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants