0

I have the current data structure in my redux state

const state = {
    chats: {
        id: "idhere",
        messages: [
            { 
               obj: "here" 
            },
            { 
               obj: "here" 
            },
        ]
    }
}

I want to append a result return from my action created to the end of the messages array without mutating it. I understand how I would achieve this if the messages array was a direct child of the state but as it's nested it has completely thrown me.

This is how I've got it at the moment but I'm using push, and it doesn't 'feel' right.

case GET_CHAT_MESSAGES:
    return { ...state, chats: { ...state.chats[action.id].messages: ...state.chats.[action.id].messages, action.payload }}

Thanks

1 Answer 1

3

This is how to do that in immutable way:

const state = {
    chats : {
        id: "idhere",
        messages: [
            { 
               obj: "here" 
            },
            { 
               obj: "here" 
            },
        ]
    }
}

let newObj = {

   ...state,
   chats: {
     ...state.chats,
     messages:[...state.chats.messages, {obj:"new object"}]
   }

};

If you get the idea, you can adapt it in reducer.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for replying. I understand what you've shown there. However the problem is that it's within a chats object within the state object? How would I go about adapting that?
That looks perfect thankyou!. I've actually wrote my question wrong with regards to how the state is actually structured. The messages key is actually the chat Id but I should be able to use what you've show above to make. Thankyou!
Accepted, Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.