Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138279

How do I properly return immutable data from a react redux reducer

$
0
0

My react redux setup was working well until I needed to trigger a component update based on an update to a redux store variable. From research I feel that my issue is that I am not returning from my reducer in an immutable fashion such that an update is not triggered in the connected component after I dispatch an update to the redux store.

Action

import {GAMESETUP_IN, GAMESETUP_OUT} from "../api/strings";

export const gameSetupIn = ({gameType, gameRound, gameStocks, gameHistory} = {}) => ({
    type: GAMESETUP_IN,
    gameSetup: {
      gameType,
      gameRound,
      gameStocks,
      gameHistory
    }
});

export const gameSetupOut = () => ({
    type: GAMESETUP_OUT
});

Reducer

// default state
import {GAMESETUP_IN, GAMESETUP_OUT} from "../api/strings";

const gameSetupReducerDefaultState = {
    gameType: "",
    gameRound: "",
    gameStocks: [],
    gameHistory: []
};

// reducer which is a pure function
export default(state = gameSetupReducerDefaultState, action) => {
    switch (action.type) {
        case GAMESETUP_IN:
            // Return a new array
            return {
                ...state,
                gameType: action.gameSetup.gameType.toString(),
                gameRound: action.gameSetup.gameRound.toString(),
                gameStocks: action.gameSetup.gameStocks,
                gameHistory: action.gameSetup.gameHistory
            };
        case GAMESETUP_OUT:
            return {
                ...state,
                gameType: "",
                gameRound: "",
                gameStocks: [],
                gameHistory: []
            };
        default:
            return state;
    }
};

I feel like there are two very closely related questions. 1) How can I return immutable data from redux reducer? 2) Updating Redux state does not trigger componentWillReceiveProps

and also the base redux documentation 3) https://redux.js.org/basics/reducers/

I feel like the answer is right in front of me that I need to somehow use return Object.assign({}, state, { key: newValue }); during the return from redux. I am just looking for some help in modifying my reducer to ensure that it is immutable and thus will trigger a component update after a dispatch. Thank you.


Viewing all articles
Browse latest Browse all 138279

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>