Skip to content

dhmk083/dhmk-atom

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@dhmk-atom

MobX-like observable atoms, computeds and observers.

Install: npm install @dhmk/atom

Example

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();

API

atom(value: T, opts?: AtomOptions): WritableAtom<T>

Creates a value atom which is similar to MobX observable.box(value, { deep: false }).

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;
};

atom(fn: () => T, opts?: ComputedAtomOptions): Atom<T>

Creates a computed atom which is similar to MobX computed.

type ComputedAtomOptions = {
  equals?: (next: T, prev: T) => boolean;
  onBecomeObserved?: () => void;
  onBecomeUnobserved?: () => void;
};

type ComputedAtom<T> = {
  (): T;
  get(): T;
};

observable(x)

Creates observable object or array. See also observableObject, observableArray, as.

observe(fn: (self: Observer) => void, opts?: ObserverOptions): Observer

Similar to MobX autorun.

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;
};

act(fn: () => T): T

MobX runInAction.

untracked(fn: () => T): T

MobX untracked.

as(x: { get, set? })

Instructs observableObject to initialize property as given object instead of default behavior.

observableObject(x)

observableObject({
  id: 123,
  get computedProp() {
    return this.id.toString();
  },
  withOptions: as(atom("abc", { onBecomeObserved() {} })),
});

observableArray(x)

ValueAtom

ComputedAtom

EffectAtom

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published