> Redux - Counter Example

Redux - Counter Example


  1. Single source of truth
    The state of your whole application is stored in an object tree within a single store.
  2. State is Read-Only
    The only way to change the state is to emit an action, an object describing what happened.
  3. Changes are made with pure functions
    To specify how the state tree is transformed by actions, you write pure reducers.

Counter:
        // reducer function - pure function - principle #3
        function counter(state, action) {
          if (typeof state === 'undefined') {
            return 0
          }
          switch (action.type) {
            case 'INCREMENT':
              return state + 1
            case 'DECREMENT':
              return state - 1
            default:
              return state
          }
        }
        // create redux store - single source of truth - principle #1
        var store = Redux.createStore(counter)
      
          // get UI element to render
          var valueEl = document.getElementById('counterValue')

          function render() {
            valueEl.innerHTML = store.getState().toString()
          }

          // initial rendering (will render 0)
          render();
          // store subscribes to render(), so for every action, it will call this render()
          store.subscribe(render)

        
          // buttons click event listeners

          document.getElementById('increment')
            .addEventListener('click', () => {
              // emit action - principle #2
              store.dispatch({
                type: 'INCREMENT'
              })
            })
          document.getElementById('decrement')
            .addEventListener('click', () => {
              store.dispatch({
                type: 'DECREMENT'
              })
            })

          document.getElementById('incrementIfOdd')
            .addEventListener('click', () => {
              if (store.getState() % 2 !== 0) {
                store.dispatch({
                  type: 'INCREMENT'
                })
              }
            })

          const TIMEOUT_PERIOD = 1000;

          document.getElementById('incrementAsync')
            .addEventListener('click', () => {
              setTimeout(function() {
                store.dispatch({
                  type: 'INCREMENT'
                })
              }, TIMEOUT_PERIOD)

            })

        

References
  1. Three Principles - Dan Abramov