Louis
Louis

Reputation: 438

How to add data to redux state array without any id in a reducer?

I've got this reducer :

import { GET_CHAT, ADD_MESSAGE } from '../actions';

export default function (state = null, action) {
switch (action.type) {
    case GET_CHAT:
        return { ...state, [action.meta.id]: action.payload.data };
    case ADD_MESSAGE:
        console.log(state[action.meta.convId].chat.messages)
        return {
            ...state,
            [action.meta.convId]: {
                ...state[action.meta.convId],
                chat: {
                    ...state[action.meta.convId].chat,
                    messages: {
                        ...state[action.meta.convId].chat.messages,
                        action.payload
                    }
                }
            }
        };
    default:
        return state;
}
}

Where I want to add the action.payload to the end of the messages array. The issue is : when I try to put a key to the payload like so :

[action.meta._id]:action.payload

Messages is not an array anymore but becomes an object. So i can't loop over it anymore with map(). And redux won't let me push the payload directly to the array, it seems like i must put a key ... Any help would be appreciated, thank's :)

Upvotes: 2

Views: 998

Answers (1)

cdaiga
cdaiga

Reputation: 4939

If you want your messages to always be an array then your reducer should be like below:

import { GET_CHAT, ADD_MESSAGE } from '../actions';

export default function (state = null, action) {
  switch (action.type) {
    case GET_CHAT:
       return { ...state, [action.meta.id]: action.payload.data };
    case ADD_MESSAGE:
        console.log(state[action.meta.convId].chat.messages)
        return {
           ...state,
           [action.meta.convId]: {
               ...state[action.meta.convId],
               chat: {
                  ...state[action.meta.convId].chat,
                  messages: [                                //USE SQUARE BRACKETS INSTEAD
                    ...state[action.meta.convId].chat.messages,
                    action.payload
                  ]
               }
          }
        };
    default:
      return state;
    }
}

Upvotes: 2

Related Questions