Skip to content

Instantly share code, notes, and snippets.

const subscribeMiddleware = () => store => {
let handlers = [];
store.subscribe = (cb) => {
handlers = handlers.concat(cb);
const removeSubscriber = () => { handlers = handlers.filter(fn => fn !== cb) };
return removeSubscriber;
};
return next => (action) => {
const createStore = ({
reducer = state => state,
middlewares = [],
initialState = undefined,
}) => {
const store = {};
store.dispatch = combineMiddlewares([
...middlewares,
reducerMiddleware(reducer, initialState)
const reducerMiddleware = (reducer, initialState) => store => {
let state = initialState;
store.getState = () => state;
return () => (action) => { state = reducer(state, action); };
};
const createStore = ({ middlewares = [] }) => {
const store = {};
store.dispatch = combineMiddlewares(middlewares)(store);
return store;
};
const combineMiddlewares = middlewares => (store) => {
const propagationFunctions = middlewares.map(middleware => (
middleware(store)
));
const invokeMiddlewareChain = propagationFunctions.reduceRight((nextFn, propagationFunction) => (
propagationFunction(nextFn)
), null);
return invokeMiddlewareChain;
};
const middleware = () => store => next => action => {
// Get the state before and after the action was performed
const previousToken = store.getState().token;
next(action);
const nextToken = store.getState().token;
// Respond to changes
if (nextToken !== previousToken) localStorage.setItem('token', nextToken);
};
const middleware = musicPlayer => store => {
const playbackOrigin = 'playbackOrigin';
musicPlayer.on('current-time-changed', currentTime => {
store.dispatch({ type: 'SET_CURRENT_TIME', origin: playbackOrigin, currentTime });
});
musicPlayer.on('playback-finished', () => {
store.dispatch({ type: 'STOP_PLAYING', origin: playbackOrigin });
});
const middleware = () => store => {
const fileWatcher = new FileWatcher();
fileWatcher.on('file-changed', filename => {
store.dispatch({ type: 'FILE_CHANGED', filename });
});
// Make sure we're watching files that may be included in the store's initial state
const initialFiles = store.getState().activeFiles;
fileWatcher.watchFiles(initialFiles);
const fetch = (url, params) => ({
type: 'FETCH',
url,
params,
});
const fetchMiddleware = fetchImplementation => store => next => action => {
if (action.type === 'FETCH') {
const { url, params } = action;
const token = store.getState().token;
import { createStore, applyMiddleware, combineReducers } from 'redux';
const middlewares = applyMiddleware(
thunk,
fetchMiddleware(fetch, 'http://api.server.com')
);
const store = createStore(reducers, initialState, middlewares);