Last active
August 6, 2018 14:16
-
-
Save SuperOleg39/8d44a0d232b5b7fdf5bc0f2c08585f6c to your computer and use it in GitHub Desktop.
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 { 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