Created
December 8, 2016 04:21
-
-
Save aamnah/30dc262e65e593ea0981d284f209db5c to your computer and use it in GitHub Desktop.
Redux: Basic Counter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createStore, applyMiddleware } from 'redux' | |
| import createLogger from 'redux-logger' // logger so i don't have to manually log state before & after every dispatched action | |
| // REDUCER | |
| const counter = (state = 0, action) => { | |
| switch(action.type) { | |
| case 'INCREMENT': | |
| return state + 1 | |
| case 'DECREMENT': | |
| return state - 1 | |
| default: | |
| return state | |
| } | |
| } | |
| // STORE + MIDDLEWARE | |
| const logger = createLogger() | |
| const store = createStore( | |
| counter, | |
| applyMiddleware(logger) | |
| ) | |
| // SUBSCRIBE | |
| const showCounter = () => { | |
| document.querySelector('#root').innerText = store.getState() | |
| } | |
| store.subscribe(showCounter) | |
| showCounter() | |
| // DISPACTH 'INCREMENT' ACTIONS on CLICK | |
| document.addEventListener( 'click', () => { | |
| store.dispatch({ type: 'INCREMENT' }) | |
| }) | |
| // DISPATCH | |
| store.dispatch({ type: 'INCREMENT' }) | |
| store.dispatch({ type: 'INCREMENT' }) | |
| store.dispatch({ type: 'INCREMENT' }) | |
| store.dispatch({ type: 'DECREMENT' }) | |
| store.dispatch({ type: 'INCREMENT' }) | |
| store.dispatch({ type: 'DECREMENT' }) | |
| store.dispatch({ type: 'DECREMENT' }) | |
| store.dispatch({ type: 'INCREMENT' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment