I'm trying to create a reducer without the benefit of ES6. It's an old PHP app with no build process to leverage for transpilation.
I'm initializing state:
let defaultState = {
accountTypes: {
personal: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
},
business: {
selected: false,
checking: {
selected: false
},
savings: {
selected: false
}
}
}
};
Here's the reducer and then the store init:
function reducer(state, action) {
switch (action.type) {
case 'TOGGLE_ACCOUNT_TYPE':
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
console.log(action.payload);
// {
// personal: {selected: true}
// }
let blah = Object.assign({}, state, {
accountTypes: Object.assign({}, state.accountTypes, action.payload)
});
console.log(blah.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: true}
// }
return blah;
default:
return state;
}
}
const store = Redux.createStore(reducer, defaultState);
let state = store.getState();
Subscribing to state later, inside jQuery's document.ready
:
store.subscribe(function () {
console.log(state.accountTypes);
// {
// business: {selected: false, checking: {…}, savings: {…}}
// personal: {selected: false, checking: {…}, savings: {…}}
// }
You can see that the state isn't updated with the action payload.
I think I've just stumbled on my answer. Posting the question jarred something loose. I was using a stale state variable for my jQuery operations.
store.subscribe(function () {
// update the state var
state = store.getState();
If there's a better way to use a state variable without having to manually refresh it, please post another answer.