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.

Revisions

  1. Benjamin Verble revised this gist Sep 22, 2016. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions naive-redux-middleware.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,6 @@
    import { createStore, combineReducers } from 'redux'

    // for webpackbin
    const log = typeof bin.log === 'function' ? bin.log : console.log;

    function reducer (state = 0, action) {
  2. Benjamin Verble created this gist Sep 22, 2016.
    69 changes: 69 additions & 0 deletions naive-redux-middleware.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    import { createStore, combineReducers } from 'redux'

    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))