skip to Main Content

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;

2

Answers


  1. 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}));
    
    Login or Signup to reply.
  2. Your MapType is object but you are trying to call it as array.

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

    Also MapType is a object which mean that key can be only string

    P.S It’s better to use Record<string, string[]> for MapType

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search