Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading