Skip to content

Instantly share code, notes, and snippets.

@aamnah
Created December 8, 2016 04:21
Show Gist options
  • Select an option

  • Save aamnah/30dc262e65e593ea0981d284f209db5c to your computer and use it in GitHub Desktop.

Select an option

Save aamnah/30dc262e65e593ea0981d284f209db5c to your computer and use it in GitHub Desktop.
Redux: Basic Counter example
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