Skip to content
Advertisement

How to update the state in React Redux?

I’m using a reducer to set the state in Redux. My state currently looks something like this.

JavaScript

In my old reducer, I was just getting the conversations array and setting that but now I need access to the activeConversation string as well. Therefore, I decided to use my root reducer which combines everything so it can work correctly. Here’s my root reducer.

JavaScript

My setNewMessage function is called which then calls addMessageToStore.

JavaScript

The problem with this is that next state isn’t being updated. When it returns next state, it just shows the previous state instead of my new one. Does anyone know what’s going on?

Advertisement

Answer

I think you are “cutting” your state slices inefficiently. At best, a Reducer should always own their own state, and you are right now going to great lengths to have a meta-reducer for conversations to have access to the activeConversation.

Why not have a normal reducer for both?

Have a state of the shape

JavaScript

where conversations has the shape

JavaScript

That way your conversations reducer has just access to it’s own state properties – items and active – and does not need to to any gymnastics.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement