Skip to content

Instantly share code, notes, and snippets.

@MaxMotovilov
Last active April 16, 2020 16:18
Show Gist options
  • Save MaxMotovilov/780cdcb57433f254f62020e8c032f968 to your computer and use it in GitHub Desktop.
Save MaxMotovilov/780cdcb57433f254f62020e8c032f968 to your computer and use it in GitHub Desktop.
Triggers for Redux - perform imperative actions & dispatches on specific changes in the store w/o touching React components
import {bindActionCreators} from 'redux';
export function withSelectors(...selectors) {
const bound = selectors.pop();
return (...args) => {
const state = args[args.length-1].getState();
return bound(...selectors.map( sel => sel(state) ), ...args);
}
}
export function withActions(...actions) {
const bound = actions.pop();
return (...args) => {
const {dispatch} = args[args.length-1];
return bound(...actions.map( act => bindActionCreators(act, dispatch) ), ...args);
}
}
export function createTrigger(selector, trigger, hasChanged= (next, last) => last!==next) {
let lastValue;
return store => {
const newValue = selector(store.getState());
if(hasChanged(newValue, lastValue)) {
const copyLastValue = lastValue;
lastValue = newValue;
trigger(newValue, copyLastValue, store);
}
}
}
export function bindTriggers(store, triggers, onerror= err => {throw err}) {
return store.subscribe(
() => triggers.forEach(
trigger => {
try { trigger(store) } catch(err) { onerror(err, trigger) }
}
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment