Skip to content

Instantly share code, notes, and snippets.

@SuperOleg39
Last active August 6, 2018 14:16
Show Gist options
  • Select an option

  • Save SuperOleg39/8d44a0d232b5b7fdf5bc0f2c08585f6c to your computer and use it in GitHub Desktop.

Select an option

Save SuperOleg39/8d44a0d232b5b7fdf5bc0f2c08585f6c to your computer and use it in GitHub Desktop.
import { Store, Unsubscribe } from 'redux';
const defaultEqual = <P>(prev: P, next: P) => prev === next;
const defaultImmediately = true;
interface IWatcherParams<S, V, P> {
store: Store<S>;
selector: (state: S, params?: P) => V;
onChange: (prev: V, next: V) => void;
props?: P;
equal?: (prev: V, next: V) => boolean;
immediately?: boolean;
}
const createWatcher = <S, V, P = undefined>(
{ store, selector, onChange, props, equal = defaultEqual, immediately = defaultImmediately }: IWatcherParams<S, V, P>,
): Unsubscribe => {
let initial = selector(store.getState(), props);
if (immediately) {
onChange(initial, initial);
}
return store.subscribe(() => {
const prev = initial;
const next = selector(store.getState(), props);
if (!equal(prev, next)) {
initial = next;
onChange(prev, next);
}
});
};
export { createWatcher };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment