BC00 BC00 - 1 month ago 18
React JSX Question

react/redux nested state issue

I am new to react/redux and I am trying to store one of my objects in redux state as a Map/Hash with the keys being the primary keys from the objects from the db and the values being the object itself. However the state seems to get overidden each time I am updating and the new value I am adding is the only one that remains. Here is my code:

import { RECEIVE_CURRENT_SCAN_RESULT } from '../constants';

const initialState = {
currentScanResult: {info:{}, results:[]},

export default createReducer(initialState, {
[RECEIVE_CURRENT_SCAN_RESULT]: (state, payload) =>
Object.assign({}, state, {
currentScanResult: payload


export function createReducer(initialState, reducerMap) {
return (state = initialState, action) => {
const reducer = reducerMap[action.type];

return reducer
? reducer(state, action.payload)
: state;

I would like to just pass in my object:

{id: 1, thing: "blue"}

and have the state be updated with it. Then if I pass in:

{id: 2, thing: "red"}

I would like my redux state to reflect:

currentScanResult: {1: {id: 1, thing: "blue"}, 2: {id: 2, thing: "red"}}

Is there any easy way for me to do this? Will redux re-render if I am updating a nested value? For example if I pass in:

{id: 2, thing: "purple"}

=> currentScanResult: {1: {id: 1, thing: "blue"}, 2: {id: 2, thing: "purple"}}

I would like to see a behavior like this. Ive looked into Immutable JS I am just wondering if I can make this simple use case work without it?

Any help is appreciated! Thanks!

Answer Source

When you do

Object.assign({}, state, {
    currentScanResult: payload

you are overriding state.currentScanResult. If you want to update it, you need to do something like

Object.assign({}, state, {
    currentScanResult: Object.assign(state.currentScanResult, payload)