'How to apply a seach function in react-table

Goal:
Create search function that filter the specified table based on input data in the input box.

Problem:
I tried to find a solution but I failed.

Info:
*You also should take account that there are more 1 table in the same page.
One search function is only for single table. It should not affect the other table
*Newbie in react-table
*Using React TS.

Stackblitz:
https://stackblitz.com/edit/react-ts-hmzvub

Thank you!


App.tsx

import React, { useState, useMemo, useEffect } from 'react';
import TodoGrid from './Grid';
import axios from 'axios';
import { useTable, Column, useSortBy } from 'react-table';
import './style.css';

interface Data {
  login: number;
  id: string;
  node_id: string;
  type: string;
}

export default function App() {
  const [todoData, setTodoData] = useState<Data[]>([]);

  React.useMemo(
    () =>
      handleData().then((res) => {
        setTimeout(() => {
          setTodoData(res);
        }, 1000);
      }),
    []
  );
  const columns: Column<Data>[] = [
    {
      Header: 'login',
      accessor: 'login',
    },
    {
      Header: 'id',
      accessor: 'id',
    },
    {
      Header: 'node id',
      accessor: 'node_id',
    },
    {
      Header: 'type',
      accessor: 'type',
    },
  ];

  async function handleData() {
    const handleDataaa = async () => {
      const resp = await axios.get('https://api.github.com/users');
      return await resp.data;
    };

    return Promise.resolve(handleDataaa());
  }

  useEffect(() => {
    handleData();
  }, []);

  const gridData = useMemo(() => todoData, [todoData]);

  return (
    <div>
      <div>{<TodoGrid columns={columns} data={gridData} />}</div>
      <br />
      <div>{<TodoGrid columns={columns} data={gridData} />}</div>
    </div>
  );
}

Grid.tsx

import React, { useState, useEffect } from 'react';
import { useTable, useSortBy, Column, usePagination } from 'react-table';

interface Data {
  login: number;
  id: string;
  node_id: string;
  type: string;
}

const UsersGrid = (props) => {
  const { data, columns } = props;

  const [filteredData, setFilteredData] = useState<Data[]>(data);
  const [searchVal, setSearchVal] = useState('');

  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
    useTable(
      {
        columns,
        data,
      },
      useSortBy,
      usePagination
    );

  const handleSearch = (e) => {
    let searchVal = e.target.value;
    console.log(searchVal);
    let filter = filteredData.filter(
      (obj) =>
        obj.login.toString().toLowerCase().indexOf(searchVal.toLowerCase()) >
          -1 ||
        obj.node_id.toString().toLowerCase().indexOf(searchVal.toLowerCase()) >
          -1
    );

    console.log(filter);

    setSearchVal(searchVal);
    //console.log('asdf', filter);
    //setData(filter);
  };

  return (
    <div>
      <input type="text" value={searchVal} onChange={handleSearch} />

      <br />
      <br />
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                  {console.log(column.getSortByToggleProps())}
                  {column.render('Header')}
                  <span>
                    {' '}
                    {column.isSorted
                      ? column.isSortedDesc
                        ? ' 🔽'
                        : ' 🔼'
                      : ''}{' '}
                  </span>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                  );
                })}
              </tr>
            );
          })}
          {rows.length === 0 && (
            <tr>
              <td colSpan={2}>loading...</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
};

export default UsersGrid;

react-table.d.tsx

import {
  UseSortByColumnOptions,
  UseSortByColumnProps,
  UseSortByInstanceProps,
  UseSortByOptions,
  UseSortByState,
} from 'react-table';

declare module 'react-table' {
  export interface TableOptions<D extends object> extends UseSortByOptions<D> {}

  export interface TableInstance<D extends object = {}>
    extends UseSortByInstanceProps<D> {}

  export interface TableState<D extends object = {}>
    extends UseSortByState<D> {}

  /*
  export interface Column<D extends object = {}>
    extends UseSortByColumnOptions<D> {}
  */
  export interface ColumnInstance<D extends object = {}>
    extends UseSortByColumnProps<D> {}
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source