Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]) 
      },
      ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading