import React from 'react'
import ReactDOM from 'react-dom/client'
import {
QueryClient,
QueryClientProvider,
keepPreviousData,
useQuery,
} from '@tanstack/react-query'
import { createStore, useStore } from '@tanstack/react-store'
import './index.css'
import {
createColumnHelper,
getInitialTableState,
rowPaginationFeature,
tableFeatures,
useTable,
} from '@tanstack/react-table'
import { fetchData } from './fetchData'
import type { Person } from './fetchData'
const queryClient = new QueryClient()
const _features = tableFeatures({
rowPaginationFeature,
})
const columnHelper = createColumnHelper<typeof _features, Person>()
const columns = columnHelper.columns([
columnHelper.accessor('firstName', {
header: 'First Name',
cell: (info) => info.getValue(),
}),
columnHelper.accessor('lastName', {
header: 'Last Name',
cell: (info) => info.getValue(),
}),
columnHelper.accessor('age', {
header: 'Age',
}),
columnHelper.accessor('visits', {
header: 'Visits',
}),
columnHelper.accessor('status', {
header: 'Status',
}),
columnHelper.accessor('progress', {
header: 'Profile Progress',
}),
])
const myTableStore = createStore(
getInitialTableState(_features, {
pagination: { pageIndex: 0, pageSize: 10 },
}),
)
function App() {
const rerender = React.useReducer(() => ({}), {})[1]
// Subscribe to store state for reactive updates
const state = useStore(myTableStore, (state) => state)
const dataQuery = useQuery({
queryKey: ['data', state.pagination],
queryFn: () => fetchData(state.pagination),
placeholderData: keepPreviousData, // don't have 0 rows flash while changing pages/loading next page
})
const defaultData = React.useMemo(() => [], [])
const table = useTable({
_features,
_rowModels: {},
columns,
data: dataQuery.data?.rows ?? defaultData,
rowCount: dataQuery.data?.rowCount,
store: myTableStore,
manualPagination: true, // we're doing manual "server-side" pagination
debugTable: true,
})
return (
<div className="p-2">
<div className="h-2" />
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder ? null : (
<table.FlexRender header={header} />
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getAllCells().map((cell) => (
<td key={cell.id}>
<table.FlexRender cell={cell} />
</td>
))}
</tr>
))}
</tbody>
</table>
<div className="h-2" />
<div className="flex items-center gap-2">
<button
className="border rounded p-1"
onClick={() => table.firstPage()}
disabled={!table.getCanPreviousPage()}
>
{'<<'}
</button>
<button
className="border rounded p-1"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
{'<'}
</button>
<button
className="border rounded p-1"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
{'>'}
</button>
<button
className="border rounded p-1"
onClick={() => table.lastPage()}
disabled={!table.getCanNextPage()}
>
{'>>'}
</button>
<span className="flex items-center gap-1">
<div>Page</div>
<strong>
{state.pagination.pageIndex + 1} of{' '}
{table.getPageCount().toLocaleString()}
</strong>
</span>
<span className="flex items-center gap-1">
| Go to page:
<input
type="number"
min="1"
max={table.getPageCount()}
defaultValue={state.pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
table.setPageIndex(page)
}}
className="border p-1 rounded w-16"
/>
</span>
<select
value={state.pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
{dataQuery.isFetching ? 'Loading...' : null}
</div>
<div>
Showing {table.getRowModel().rows.length.toLocaleString()} of{' '}
{dataQuery.data?.rowCount.toLocaleString()} Rows
</div>
<div>
<button onClick={() => rerender()}>Force Rerender</button>
</div>
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
)
}
const rootElement = document.getElementById('root')
if (!rootElement) throw new Error('Failed to find the root element')
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
)