Simple Redux

A minimal example of Redux

by John Kiran

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js"></script>
<div id="counter">-</div>
<button id="button">Inc</button>

JavaScript

var initialState = {counter: 0}
var store = Redux.createStore(reducer, initialState)

function render(state) {
  document.getElementById('counter').textContent = state.counter;
}

document.getElementById('button').addEventListener('click', function() {
  incrementCounter()
})

function incrementCounter() {
  store.dispatch({
    type: 'INCREMENT'
  })
}

function reducer(state, action) {
  if (action.type === 'INCREMENT') {
    state = Object.assign({}, state, {counter: state.counter + 1})
  }
  return state
}

store.subscribe(function() {
  render(store.getState())
})

// Render the initial state
render(store.getState())