Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 614
Nagabhushan Baddi Avatar asked Oct 28 '25 07:10

Nagabhushan Baddi


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.

like image 161
CertainPerformance Avatar answered Oct 30 '25 23:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!