Plain Redux app w/o "connect()"
/*
Attempt to do the following,
- fix the "divide by zero" display bug
- add a feature allowing the user to select multiplication or division
*/
const Redux = require('redux');
// Action creators
const actions = {
chooseDividend: (value) => ({ type: 'choose-dividend', payload: value }),
chooseDivisor: (value) => ({ type: 'choose-divisor', payload: value })
};
// Implement the "brains" of this app as a Redux store
const initialState = {
dividend: null,
divisor: null
};
const store = Redux.createStore((state = initialState, action) => {
switch(action.type) {
case 'choose-dividend': {
return {
...state,
dividend: action.payload
};
}
case 'choose-divisor': {
return {
...state,
divisor: action.payload
};
}
default: {
return state;
}
}
});
// Connect actions to the UI
const UI = {
chooseDividend: (value) => {
store.dispatch(actions.chooseDividend(value));
},
chooseDivisor: (value) => {
store.dispatch(actions.chooseDivisor(value));
},
render: () => {
const state = store.getState();
const hasDivisor = (state.divisor !== null);
const hasDividend = (state.dividend !== null);
const divisorDisplay = hasDivisor ? state.divisor : '???';
const dividendDisplay = hasDividend ? state.dividend: '???';
const resultDisplay = (hasDivisor && hasDividend) ? state.dividend / state.divisor : '???';
console.log(`${dividendDisplay} / ${divisorDisplay} = ${resultDisplay}`);
}
};
// Re-display the UI when the state changes by displaying it in the console
store.subscribe(() => UI.render());
// Interact with the UI
UI.chooseDividend(2);
UI.chooseDivisor(2);
UI.chooseDividend(6);
UI.chooseDivisor(null);
UI.chooseDivisor(4);
UI.chooseDivisor(0); // Ahh!! A bug!
no comments