How to use Mapped Types with React.useState?

I’m trying to figure out how to use Mapped Types with React UseState

import * as React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  type MapType = {
    [id: number]: string[];
  };

  let id_sab: number = 1;
  let sab: string[] = ["a", "b"]

  let scde: string[] = ["c", "d", "e"];
  let id_scde: number = 2

  const [map, setMap] = React.useState<MapType>({
      [id_sab] : sab 
  });


  React.useEffect(() => {

      // How to add a new key-value pair map[id_scde] = scde ?

    setMap(map => [...map, map[id_scde] = scde]) // This gives error. How to do it correctly?
  }, []);


  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
      </header>
    </div>
  );
}

export default App;

>Solution :

The problem is not with the react or typescript. The issue is that you are using invalid javascript syntax.

In the initial value you are assigning the property to an object, therefore, you should use : instead of =.

{
      [id_sab]: sab 
}

in the setMap you are setting an array; however, your type is an object. Thus, you have to change the syntax to:

setMap((map) => ({...map}));

And to change id_scde property you should use the following syntax:

setMap((map) => ({...map, [id_scde]: scde}));

Leave a Reply