Search code examples
javascriptreactjsreduxstore

Mutating Redux Store Array of Objects in ReactJS


My store consists of an array of objects as such:

const INIT_STATE = {
  users:[],
  contacts : []
};

And i am attempting to change mutate the store array like this:

const App = (state = INIT_STATE, action) => {
  switch (action.type) {
    case BLOCK_CONTACT:
      state.contacts.map((contact, index) => {

        if (contact._id === action.payload) {
          state.contacts[index].status = "blocked;
          return {
            ...state
          };
        }
        return {
          ...state
        };
      })
      return {
        ...state
      };
   }
}

But my store value does not change. When i log the state value after the if statement, i get the correct state values but my state is not being updated. I think it might have something to do with my return statement but at this point i have tried different variations with no luck.

Any help will be appreciated.


Solution

  • I figured it out. Incase anyone else that might need help on this, here is the code...

    const App = (state = INIT_STATE, action) => {
      switch (action.type) {
        case BLOCK_CONTACT:
          var list = state.contacts.map(contact => {
            var blockList = {
              ...contact
            };
    
            if (contact._id === action.payload) {
              blockList.status = 1;
            }
            return blockList;
          })
          return {
            ...state,
            contacts: list
          };
       }
    }