Last active
June 25, 2018 21:18
-
-
Save wesleytodd/d95fb4d2ccb0f2e5bf5569eb3d8ac253 to your computer and use it in GitHub Desktop.
A simple state container and express middlware wrapper (redux like)
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
const React = require('react') | |
const ReactDOM = require('react-dom') | |
const createStore = require('./state-container') | |
module.exports = storeMiddleware | |
function storeMiddleware (reducer, initialState, Component) { | |
let _c = Component | |
if (_c && !_c.hasOwnProperty('$$typeof')) { | |
_c = React.createFactory(Component) | |
} | |
return function (req, res, next) { | |
// Create the store | |
const store = createStore(reducer, initialState) | |
res.locals.store = store | |
// Override render method | |
res.render = function renderComponent (Comp) { | |
let __c = Comp || _c | |
if (!__c.hasOwnProperty('$$typeof')) { | |
__c = React.createFactory(__c) | |
} | |
let el = document.getElementById('app') | |
ReactDOM.render(__c(store.getState()), el) | |
store.subscribe(() => { | |
ReactDOM.render(__c(store.getState()), el) | |
}) | |
} | |
next() | |
} | |
} |
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
module.exports = createStore | |
function createStore (reducer, initialState) { | |
let state = initialState | |
const listeners = [] | |
function dispatch (action) { | |
if (typeof action === 'function') { | |
return action(dispatch) | |
} | |
if (typeof action.then === 'function') { | |
return action.then(dispatch, dispatch) | |
} | |
let _s = state | |
state = reducer(state, action) | |
// Call subscribers | |
listeners.forEach((listener) => listener(state, _s, action)) | |
return action | |
} | |
function subscribe (listener) { | |
let subscribed = true | |
listeners.push(listener) | |
return () => { | |
if (!subscribed) { | |
return | |
} | |
subscribed = false | |
listeners.splice(listeners.indexOf(listener), 1) | |
} | |
} | |
function getState () { | |
return state | |
} | |
return { dispatch, subscribe, getState } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment