Skip to content

Custom Global filtering ignores data of type dayjs #5998

Closed
@MarcusUMN

Description

@MarcusUMN

TanStack Table version

v8.21.3

Framework/Library version

18.2.0

Describe the bug and the steps to reproduce it

Issue is when my data is a dayjs object and I attempt to use a custom globalFilterFn that column will not be ran through when applying a custom global filter.

In the example below the console.log statement will only print columnId pizza when I should also see columnId startDate and columnId endDate

interface DataType {
  startDate: dayjs.Dayjs;
  endDate: dayjs.Dayjs;
  pizza: 'pepperoni' | 'cheese';
}

Code below:

import React, { useState } from 'react';
import dayjs from 'dayjs';
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  useReactTable,
} from '@tanstack/react-table';

const baseStartDate = dayjs().subtract(2, 'year').startOf('year');
const baseEndDate = dayjs().subtract(1, 'year').startOf('year');
interface DataType {
  startDate: dayjs.Dayjs;
  endDate: dayjs.Dayjs;
  pizza: 'pepperoni' | 'cheese';
}

const createData = (count: number): DataType[] => {
  const data: DataType[] = [];
  for (let i = 0; i < count; i++) {
    const startDate = baseStartDate.add(i * 3, 'days');
    const endDate = baseEndDate.add(i * 2, 'days');
    
    data.push({
      startDate,
      endDate,
      pizza: Math.random() > 0.5 ? 'pepperoni' : 'cheese',
    });
  }
  return data;
};
  const customGlobalFilterFn = (row, columnId, filterValue) => {
    console.log("columnId",columnId);
    if (columnId === 'pizza'){
      return row.getValue(columnId).toLocaleLowerCase().includes(filterValue.toLocaleLowerCase());
    }
    const rowValue = dayjs(row.original[columnId])
      .format('MMMM D, YYYY')
      .toLowerCase();
    const formattedFilterValue = filterValue.toString().toLowerCase();
    return rowValue.includes(formattedFilterValue);
  };


export const DataTable = () => {
  const [globalFilter, setGlobalFilter] = useState('');
    const [data] = React.useState<any>(() => createData(50));

  const columns = React.useMemo<ColumnDef<any, any>[]>(
    () => [
      {
        accessorKey: 'startDate',
        header: 'Start Date',
        cell: info => (info.getValue() as dayjs.Dayjs).format('MMMM D, YYYY'),
      },
      {
        accessorKey: 'endDate',
        header: 'End Date',
        cell: info => (info.getValue() as dayjs.Dayjs).format('MMMM D, YYYY'),
      },
      {
        accessorKey: 'pizza',
        header: 'Type of Pizza',
      }
    ],
    []
  );

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    globalFilterFn: customGlobalFilterFn,
    state: {
      globalFilter,
    },
    onGlobalFilterChange: setGlobalFilter,
  });

  return (
    <div>
      <div style={{ margin: '1rem 0' }}>
        <input
          value={globalFilter ?? ''}
          onChange={e => setGlobalFilter(e.target.value)}
          placeholder="Search dates..."
        />
      </div>

      <div className="p-2" style={{ overflowX: 'auto', width: '100%' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            {table.getHeaderGroups().map(headerGroup => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map(header => {
                  return (
                    <th key={header.id} colSpan={header.colSpan} style={{ border: '1px solid #ddd', padding: '8px' }}>
                  
                          {flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                    </th>
                  )
                })}
              </tr>
            ))}
          </thead>
          <tbody>
            {table.getRowModel().rows.map(row => {
              return (
                <tr key={row.id}>
                  {row.getVisibleCells().map(cell => {
                    return (
                      <td key={cell.id} style={{ border: '1px solid #ddd', padding: '8px' }}>
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </td>
                    )
                  })}
                </tr>
              )
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

Your Minimal, Reproducible Example - (Sandbox Highly Recommended)

N/A

Screenshots or Videos (Optional)

Screen.Recording.2025-04-24.at.1.53.57.PM.mov

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

No, because I do not know how

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions