BC00
BC00

Reputation: 1639

React/Redux Component not re-rendering

I am having a problem with a react component not re-rendering even though I see the state being properly updated. I am using redux, I have read state mutation is often the issue/cause of this I just dont think I am doing that. The value I am updating is nested 3 levels deep within the state.

Here is the code:

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

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

[RECEIVE_CURRENT_SCAN_RESULT]: (state, payload) =>
    Object.assign({}, state, {
      currentScanResult: 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;
    }
}

Upvotes: 0

Views: 149

Answers (1)

jonahe
jonahe

Reputation: 5000

In Object.assign the first argument is the "target" object,

so this line

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

is still mutating the currentScanResult property on the state.

Use an empty object as first argument in Object.assign, like you did on the first level, so the whole thing becomes:

// empty object as target here
Object.assign({}, state, {
  // empty object as target here as well
  currentScanResult: Object.assign({}, state.currentScanResult, payload)
})

and that should at least test if the the problem is a problem of mutation or if there is something else that needs fixing.

Upvotes: 1

Related Questions