How to update the React state when a parameter of the state is a Map?

Viewed 447

The state of a React component in my app is of the following type:

interface ComponentState {
    messages: Map<string, Messages[]>;
}

How to update the state of the component using setState?

I tried the following, however it changes the messages to an Object from a Map. Also, the following is not caught by TypeScript.

this.setState((prevState) => ({
    messages: {
        ...prevState.messages,
        [someKeyAsString]: someValue,
    }
}));

Is there a way to use a Map as a state property and update it in the proper way using setState and also not change the type of the parameter from Map to Object

1 Answers

While it's possible to use a Map in React, it's very odd since the code required to clone it is convoluted - you'll have to transform the Map into an entry array, then add the additional entry, then turn it back into a Map:

this.setState((prevState) => ({
    messages: new Map([
      ...(prevState.messages.entries()),
     ['someKeyAsString', 'someValue']
    ])
}));

I'd highly recommend using a plain object instead.

Related