Skip to content

Instantly share code, notes, and snippets.

@BenjaminVerble
Last active September 22, 2016 16:12
Show Gist options
  • Save BenjaminVerble/3077f34e1e2955dba62f7d7d1813de01 to your computer and use it in GitHub Desktop.
Save BenjaminVerble/3077f34e1e2955dba62f7d7d1813de01 to your computer and use it in GitHub Desktop.
import { createStore, combineReducers } from 'redux'
// for webpackbin
const log = typeof bin.log === 'function' ? bin.log : console.log;
function reducer (state = 0, action) {
if (action.type === 'INCREMENT') {
return state + 1
}
return state
}
// very naive applyMiddleware, only supports 1 middleware
// from Kevin Heis presentation
function applyMiddleware(middleware) {
return function(createStore) {
return function(reducer) {
var store = createStore(reducer);
return {
getState: store.getState,
subscribe: store.subscribe,
dispatch: function dispatch(action) {
return middleware(store)(store.dispatch)(action);
}
};
};
};
}
const logger = store => next => action => {
log('dispatching', action)
let result = next(action)
log('next state', store.getState())
return result
}
// from redux doc site
const vanillaPromise = store => next => action => {
if (typeof action.then !== 'function') {
return next(action)
}
return Promise.resolve(action).then(store.dispatch)
}
let mainReducer = combineReducers({reducer})
let store = createStore(
mainReducer,
applyMiddleware(vanillaPromise)
)
const asyncIncrementAction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.floor(Math.random() * 1000) % 2 === 0) {
resolve({type:'INCREMENT'})
} else {
const error = new Error()
error.mesage = 'mah error'
reject(error)
}
}, 1000)
})
}
store.subscribe(() => log(store.getState()))
store.dispatch({type: 'INCREMENT'})
store.dispatch({type: 'INCREMENT'})
store.dispatch({type: 'INCREMENT'})
store.dispatch(asyncIncrementAction().catch(bin.log))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment