Objective:
To refresh the content of the react-table, press the reload button.
Challenge:
The code works on StackBlitz but not on my local development computer. What am I missing?
Information:
* Using TypeScript with react-table
Stackblitz URL:
https://stackblitz.com/edit/react-ts-cbvmnt
https://i.sstatic.net/Dz9bg.png
Thank you!
app.tsx
import React, { useState, useEffect } from 'react';
import { useTable, Column, useSortBy } from 'react-table';
import axios from 'axios';
const columns: Column<Data>[] = [
{
Header: 'login',
accessor: 'login',
},
{
Header: 'id',
accessor: 'id',
},
{
Header: 'node id',
accessor: 'node_id',
},
{
Header: 'type',
accessor: 'type',
},
];
interface Data {
login: number;
id: string;
node_id: string;
type: string;
}
export default function App() {
const [data, setData] = useState([]);
React.useMemo(
() =>
fetchData().then((res) => {
setTimeout(() => {
setData(res);
}, 1000);
}),
[]
);
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable<Data>({ columns, data }, useSortBy);
async function fetchData() {
const fetchGithubUsers = async () => {
const response = await axios.get('https://api.github.com/users');
return await response.data;
};
return Promise.resolve(fetchGithubUsers());
}
useEffect(() => {
fetchData();
}, []);
const reloadTable = () => {
axios.get<Data[]>('https://api.github.com/users').then((response) => {
setData(response.data);
});
};
return (
<div>
<button onClick={reloadTable}>Reload</button>
<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>
);
}
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> {}
}