Function makeObservable

  • Enhances an object to make its properties observable using specified annotations.

    Type Parameters

    • T

    Parameters

    • obj: T

      The object to be observed.

    • annotations: {
          [key: string]: "atom" | "computed" | "collection" | "reactiveProps" | false;
      }

      Annotations defining the type of reactivity for each property. Properties with a 'false' annotation will be ignored.

      • [key: string]: "atom" | "computed" | "collection" | "reactiveProps" | false
    • Optional options: {
          name: string;
      }

      Options to configure the observable behavior.

      • name: string

        The name of the observable object. Defaults to an empty string. Using as prefix for reactive property names.

    Returns T

    The input object with enhanced reactive properties.

    Example

    class List {
    data = [];

    constructor(data) {
    this.data = data;
    makeObservable(this, { data: "collection" });
    }

    // not reactive property
    get length() {
    return this.data.length;
    }
    }

    const list = new List([1, 2, 3]);

    let foo = 0;

    autorun((updates) => {
    console.log(`list.length = ${list.length}`);
    foo++;
    });
    // Outputs: list.length = 3

    console.log(foo);
    // Outputs: 1

    list.data.push(4);
    // Outputs: list.length = 4
    console.log(foo);
    // Outputs: 2

    list.data.pop();
    // set last element to undefined. foo++
    // Outputs: list.length = 4
    // set new value of length/ foo++
    // Outputs: list.length = 3

    console.log(foo);
    // Outputs: 4

    Example

    let object = {
    value: 0,
    get double() {
    return this.value * 2;
    },
    increment() {
    this.value++;
    },
    };

    makeObservable(object, { value: "atom", double: "computed" });

    let foo = 0;

    autorun(() => {
    foo++;
    object.double;
    });
    console.log(foo); // 1

    object.increment();
    console.log(foo); // 2

    object.increment();
    console.log(foo); // 3