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
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=
.in the
setMap
you are setting an array; however, your type is an object. Thus, you have to change the syntax to:And to change
id_scde
property you should use the following syntax: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 onlystring
P.S It’s better to use
Record<string, string[]>
forMapType