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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With