Refresh the React-Table using a click of a button

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> {}
}

Answer â„–1

Your state typing is incorrect and TypeScript is issuing a warning because of it.

If you pass an empty array `[]` as the default value in `useState`, TypeScript assumes that there will never be any elements in the array, resulting in the type `never[]`. To fix this, use `useState([])` to correctly inform TypeScript about the type of the state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript and webpack 2 to integrate typeahead.js into your project

I am encountering an error message coming from webpack. ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts Module not found: Error: Can't resolve 'typeahead' in ... I have the following dependencies installed npm install ...

Error in Angular 10: Module import issue with missing name

After setting up a new Angular project and creating a new module within that project using the CLI, I encountered an issue where Intellisense was not working properly when trying to import the newly created module in app.module.ts. Despite not making any c ...

Discovering new bugs in VSCode Playwright Tests but failing to see any progress

This morning, everything was running smoothly with debugging tests. However, after a forced reboot, I encountered an issue where it seems like the debugger is running, but nothing actually happens. This has happened before, but usually resolves itself. Unf ...

Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript? Here is some sample code: type KeyUrl<T> = T extends `/${infer U}` ? U : never; type TUrl<T> = { [k in KeyUrl<T>]: string }; // ---------------------------------- ...

Angular is having trouble with disabled dates on the HTML5 Datepicker

I am encountering an issue with disabling past dates in a date-picker using HTML5. When I use the date-picker without any specific conditions, the disabled dates work as expected. However, when I try to use the date-picker with conditions, it does not fun ...

The navigation bar changes its functionality depending on the page

My Angular application features a main app component that includes a navbar linking to other components using the routerLink directive. The structure is simple: <nav> <button [routerLink]="['/foo']> Foo </button> ...

How to implement a responsive menu using the onPress attribute of TouchableOpacity

Looking to implement a profile picture upload feature with the ability to choose between getting an image from the camera (using getMediaFromCamera) or selecting one from the gallery (using getMediaFromImageLibrary). I currently have a TouchableOpacity set ...

Using React and TypeScript together can lead to issues when trying to use union keys as an index

I've implemented a hook using useState and the delete method to effectively manage my form values. const [values, setValues] = useState<tAllValues>({}); The values stored include: { name: 'Andrew', age: 34, avatar: [{ name: ...

Is it normal for TypeScript to not throw an error when different data types are used for function parameters?

function add(a:number, b:number):number { return a+b; } let mynumber:any = "50"; let result:number = add(mynumber, 5); console.log(result); Why does the console print "505" without throwing an error in the "add" function? If I had declared mynumber ...

ReactJS - Triggering a timeout reset and reactivation with a single button press

When I click a button that has a callback function, I want it to start a timeout with a 5-second delay. If the button is clicked again within that 5 seconds, I want the timer to reset without triggering the timeout handler. The handler should only be calle ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

Conceal a div when clicked outside using TypeScript with Next.js and Tailwind CSS

I am currently working on a modal using TypeScript, Next.js, and Tailwind CSS. My goal is to hide the modal when I click outside of it. However, I am encountering some errors related to types and other issues in my TSX file. The functionality works perfec ...

Using TypeScript, you can access the constructor of a derived type by calling it with the

In my TypeScript project, I am attempting to generate or duplicate a child object using a method within the base class. Here is my simplified code setup: abstract class BaseClass<TCompositionProps> { protected props: TCompositionProps; prot ...

The element 'flat' is not found within the specified type

My challenge involves utilizing the flat() method in a TypeScript script. In my tsconfig.json file, I have set the target to es2017 and defined an interface for the input variable. However, I keep encountering this error message: Property 'flat' ...

TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations. To achieve this, I have been experimenting with the data ...

Implementing Dynamic FormControl Values within FormGroup in Angular: A Step-by-Step Guide

GenerateFields(customControl, customValue): FormGroup { return this.fb.group({ customControl: new FormControl(customValue), }) } I am looking for a way to dynamically add the value of customControl from the parameter passed in the Ge ...

Multiple components are returned with switch case

I am trying to iterate over an object and display a result based on Object.entries. However, the loop currently stops at the first return statement. Is there a way for me to capture and display all components returned simultaneously, perhaps using a vari ...

Ways to simulate objects in jest

I'm facing an issue while trying to mock a function of an object using Jest and Typescript. Below is a concise version of my code: // myModule.ts export const Foo = { doSomething: () => { // ... does something console.log('original ...

Using Angular 2 to create an Observable type that mediates two separate http.get calls

In my ng2 service, I have a method that contains two http.get calls. Here is an example of the function: getInfo(userId: number): any { this.http .get(apiUrl, options) .map(response => response.json()) .subscribe(example => ...

Unexpected error in React TypeScript: '=' symbol missing. Code error TS1005

Encountering an issue: '=' expected. TS1005 5 | * LICENSE file in the root directory of this source tree. 6 | */ > 7 | import type { NewPlugin, Optionsz, OptionsReceived } from './types'; | ^ ...