Search code examples
javascriptreduxreact-reduxobject-literal

Spread syntax for Map in JavaScript


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 ?


Solution

  • This is what you're looking for:

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