I am diving into React with Redux.
I always fall into the trap of trying to skip the fundamentals.
I always choose the hard way.
You can never skip the fundamentals.
I do not understand why they put the essentials before the fundamentals but I should have known better.
Here is the story of x, my Redux pure JS all killer no filler:
<!DOCTYPE html>
<html>
<hread>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
</hread>
<body>
<p id="xValueDisplay"></p>
<input id="xValueInput" />
<button id="xValueSetter">Set</button>
<script>
// the UI
const xValueDisplayEl = document.getElementById('xValueDisplay');
const xValueInputEl = document.getElementById('xValueInput');
const xValueSetterEl = document.getElementById('xValueSetter');
// the initial state of the reducer
const appInitialState = {
x: 'change me'
}
// the reducer
function appReducer(state = appInitialState, action) {
switch (action.type) {
case 'x/wasSet':
return { ...state, x: action.payload};
default:
return state;
}
}
// the store
const appStore = Redux.createStore(appReducer);
// the UI renderer
function appRender() {
const state = appStore.getState();
xValueDisplayEl.innerHTML = state.x;
xValueInputEl.value = state.x;
}
// first render with the state of the store
appRender();
// subscribe the renderer to the store updates
appStore.subscribe(appRender);
xValueSetterEl.addEventListener('click', function() {
// we dispatch the x/wasSet action to change store state
appStore.dispatch({ type: 'x/wasSet', payload: xValueInputEl.value });
});
</script>
</body>
</html>
Top comments (0)