Skip to content

Instantly share code, notes, and snippets.

@kubk
Last active June 2, 2022 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubk/e15de48daddfb491960613faf5ea2896 to your computer and use it in GitHub Desktop.
Save kubk/e15de48daddfb491960613faf5ea2896 to your computer and use it in GitHub Desktop.
import { makeAutoObservable } from 'mobx';
import { avoidMobxAutoObservable } from './avoid-mobx-auto-observable';
import { types } from 'util';
test('avoidMobxAutoObservable allows to avoid Mobx auto conversion', () => {
class Store {
constructor(public dependency: object) {
makeAutoObservable(this);
}
}
const dependencyObservable = {};
const store = new Store(dependencyObservable);
expect(types.isProxy(store.dependency)).toBeTruthy();
const dependencyObservable2 = {};
avoidMobxAutoObservable(dependencyObservable2);
const store2 = new Store(dependencyObservable2);
expect(types.isProxy(store2.dependency)).toBeFalsy();
});
import { $mobx } from 'mobx';
/**
* If you use makeAutoObservable Mobx tries to convert object properties to observables, methods to actions and getters to computed
* Mobx skips converting foreign classes like Luxon's DateTime, History, etc
* The main rule - if object is a class instance it skips the conversion. If it is just an object, Mobx will try to convert it to observable
* Sometimes it's not what you want. That's why this function exists
*/
export const avoidMobxAutoObservable = (object: any) => {
// @ts-ignore
object[$mobx] = true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment