Spread syntax for Map in JavaScript

266 views Asked by At

In my React project (Chat App), I am using redux toolkit, I want to use Map in place of object literal {} as state.

chatMap state contains contactId (mongodb _id) as key and chat array as value.

something like that -

chatMap =
{
   [contactId1]: [chatsArr1],
   [contactId2]: [chatsArr2]
}

(chatSlice.js)

const initialState = {
   chatMap: new Map(),
   ...
}
reducers: {
      setChatMap: (state, action) => {
         state.chatMap = {...chatMap, key1: action.payload}
      },
      ...
}

How to update chatMap (Map) state ?

4

There are 4 answers

0
Ayudh On BEST ANSWER

This is what you're looking for:

reducers: {
      setChatMap: (state, action) => {
         state.chatMap = new Map([...chatMap, [key1, action.payload]]) 
      },
      ...
}
1
msx47 On

You can do something like this.

reducers: {
      setChatMap: (state, action) => {
         state.chatMap = new Map(state.chatMap).set('key1', action.payload)
      },
      ...
}
0
Shakya Peiris On

Firt you can convert the map to an object, then spread it. Again convert the final object to a map.

reducers: {
      setChatMap: (state, action) => {
         const obj = object.fromEntries(chatMap);
         const tCM = {...obj, key1: action.payload};
         state.chatMap = new Map(tCM);
      },
      ...
}
1
Versaroumane On

Your problem relies on the fact that, React has now way of knowing if your object(Map) has changed or not, since its a bit more complicated than a primitive, you need to make what's called a deep-copy of that object.

By passing a new object, react will see a new reference and then trigger a new render.

Cheers