Skip to content

Instantly share code, notes, and snippets.

@rakannimer
Last active August 31, 2017 09:46
Show Gist options
  • Save rakannimer/d9c83d9e1d21fc03e7af1e7997055755 to your computer and use it in GitHub Desktop.
Save rakannimer/d9c83d9e1d21fc03e7af1e7997055755 to your computer and use it in GitHub Desktop.
mobx reactions quick tldr
import { reaction, observable, runInAction } from 'mobx';
const myObservableMap = observable.map({});
const disposeReaction = reaction(() => myObservableMap, (newObservableValue) => {
console.warn('Someone changed the observable map. new value : ', newObservableValue);
})
myObservableMap.set('some', {data: 'of any type'})
myObservableMap.set('someOther', 'data')
// reaction will run twice.
// When I want to stop listening :
disposeReaction()
// Making the code above more testable :
const createReactionTo = (observableInstance, reactionFunction) => {
const disposeReaction = reaction(() => observableInstance, reactionFunction);
return disposeReaction;
}
const mutateObservable = (observable, mutatorFunction) => {
runInAction(mutatorFunction);
}
const myObservableMap = observable.map({});
const reactionFunction = () => { console.warn('Someone changed the observable map. new value : ' + newObservableValue); }
const disposeReaction = createReactionTo(myObservableMap, reactionFunction)
mutateObservable(() => {
myObservableMap.set('some', {data: 'of any type'})
myObservableMap.set('someOther', 'data')
})
// Now testing it should be much simpler
// Let's do it
test('can create a reaction to an observable', () => {
const myObservableMap = observable.map({});
const fakeReactionFunction = jest.fn();
const disposeReaction = createReactionTo(myObservableMap, fakeReactionFunction)
expect(fakeReactionFunction).not.toHaveBeenCalled();
myObservableMap.set('foo','fooVal')
expect(fakeReactionFunction).toHaveBeenCalled();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment