Skip to content

Instantly share code, notes, and snippets.

@inakianduaga
Last active August 16, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inakianduaga/f59ce6e7627061b98d7a6f1be21c9b51 to your computer and use it in GitHub Desktop.
Save inakianduaga/f59ce6e7627061b98d7a6f1be21c9b51 to your computer and use it in GitHub Desktop.
Redux for vanillaJS Medium.com article - Redux gallery middleware
import * as Redux from "redux";
import Config from "./config"; // some config
import { State } from "../../store/rootReducer";
import * as actions from "./actions";
import { listeners as domListeners, mutations as domMutations } from "./dom";
/**
* Middleware to schedule dom mutations based on redux actions / state changes
*/
export const middleware = (_: Config) => (
store: Redux.MiddlewareAPI<Redux.Dispatch, State>
) => {
// Register DOM listeners on middleware registration
const listeners = domListeners(store.dispatch);
listeners.onImageSelect();
listeners.onFilterSelect();
return (next: Redux.Dispatch<actions.ApplicationAction>) => (
action: actions.ApplicationAction
) => {
const prevState = store.getState();
const result = next(action);
const state = store.getState();
// Perform some mutation / side effect based on actions
switch (action.type) {
// Here we can perform asynchronous side effects
// No need for Redux Thunk or additional libraries
case actions.SELECT_IMAGE_ASYNC_TRIGGER:
setTimeout(() => store.dispatch(actions.SELECT_IMAGE), 2); // example
break;
default:
break;
}
// Perform dom mutations based on state changes
if (prevState.gallery.selected !== state.gallery.selected) {
state.gallery.selected !== null
? domMutations.select(state.gallery.selected)
: domMutations.clearSelected();
domMutations.toggleDropdownDisability(state.gallery.selected === null);
}
if (prevState.gallery.filters !== state.gallery.filters) {
domMutations.applyFiltersToImages(state.gallery.filters);
}
return result;
};
};
export default middleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment