Last active
August 16, 2018 16:54
-
-
Save inakianduaga/f59ce6e7627061b98d7a6f1be21c9b51 to your computer and use it in GitHub Desktop.
Redux for vanillaJS Medium.com article - Redux gallery middleware
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
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