@dhmk/atom
Version:
Lightweight mobx-like observable values, computed values and side-effects
121 lines (83 loc) • 2.37 kB
Markdown
and observers.
Install: `npm install @dhmk/atom`
```ts
import { observable, observe, act } from "@dhmk-atom";
const x = observable({
id: 123,
get computedProp() {
return this.id.toString();
},
});
const dispose = observe(() => console.log(x.computedProp));
act(() => (x.id = 456));
dispose();
```
Creates a value atom which is similar to MobX [observable.box(value, { deep: false })](https://mobx.js.org/api.html#observablebox).
```ts
type AtomOptions = {
equals?: (next: T, prev: T) => boolean;
onBecomeObserved?: () => void;
onBecomeUnobserved?: () => void;
set?: (setter: (x: T) => void) => (x: T) => void;
};
type WritableAtom<T> = {
(): T;
get(): T;
set(x: T): void;
};
```
Creates a computed atom which is similar to MobX [computed](https://mobx.js.org/api.html#computed).
```ts
type ComputedAtomOptions = {
equals?: (next: T, prev: T) => boolean;
onBecomeObserved?: () => void;
onBecomeUnobserved?: () => void;
};
type ComputedAtom<T> = {
(): T;
get(): T;
};
```
Creates observable object or array. See also `observableObject`, `observableArray`, `as`.
Similar to MobX [autorun](https://mobx.js.org/api.html#autorun).
```ts
type ObserverOptions = {
scheduler?: (run: Function) => void;
onBecomeObserved?: () => void;
onBecomeUnobserved?: () => void;
};
type Observer = {
// dispose
(): void;
// schedule observer for execution even if no tracked atoms were changed
invalidate(): void;
readonly isInitial: boolean;
};
```
MobX [runInAction](https://mobx.js.org/api.html#runinaction).
MobX [untracked](https://mobx.js.org/api.html#untracked).
Instructs `observableObject` to initialize property as given object instead of default behavior.
```ts
observableObject({
id: 123,
get computedProp() {
return this.id.toString();
},
withOptions: as(atom("abc", { onBecomeObserved() {} })),
});
```
MobX-like observable atoms, computeds