Skip to content

ViewModelBase class

This is the base implementation of the ViewModel interface.

Reference to source code

Methods and properties

Here is documentation about base implementation methods and properties.

INFO

If you want to read about ViewModel interface methods and properties go to interface documentation

viewModels

Reference to an instance of ViewModelStore.
Allows access to other ViewModels.

Example

ts
import { ViewModelBase } from "mobx-view-model";

export class SithCardVM extends ViewModelBase {
  get power() {
    return this.viewModels.get(JediCardVM)?.power ?? 0;
  }
}

export class StarWarsBattlefieldVM extends ViewModelBase {
  get jedisCount() {
    this.viewModels.getAll(JediCardVM).length;
  }

  get sithsCount() {
    this.viewModels.getAll(SithCardVM).length;
  }
}

unmountSignal

This is an AbortSignal that is signaled when your ViewModel is unmounted. It happens after unmount() completes in the base implementation.

Example

ts
import { ViewModelBase } from "mobx-view-model";
import { autorun } from "mobx"

export class TestVM extends ViewModelBase {
  protected willMount() {
    autorun(
      () => {
        console.log("log", this.id, this.isMounted);
      },
      {
        signal: this.unmountSignal
      }
    );
  }
}

vmConfig

Configuration object for the view model.
See ViewModelsConfig for detailed configuration options.

isMounted: boolean computed

Indicates whether the ViewModel is currently mounted with its associated component.

isUnmounting: boolean computed

Indicates whether the ViewModel is in the process of unmounting.

willMount(): void protected

Called when the component begins mounting in the React tree.
Executes before the mount() method.

mount(): void | Promise<void> action.bound

Called when the component is mounted in the React tree.

This method sets isMounted to true.
If you override this method, be sure to call super.mount(); otherwise your view component connected to this ViewModel will never be rendered because the withViewModel HOC checks the isMounted flag before rendering the view component.

This method can be async. This feature is helpful if you want to load some data or do something before the view component will be rendered

Example: Async Mounting

ts
import { ViewModelBase } from "mobx-view-model";

class JediProfileVM extends ViewModelBase<{ jediId: string }> {
  async mount() {
    await this.loadJediData();
    await super.mount();
  }

  private async loadJediData() {
    const response = await fetch(`/api/jedi/${this.payload.jediId}`);
    this.jediData = await response.json();
  }
}

didMount(): void protected

Called after the view model is fully mounted and ready for use.
Ideal for post-mount initialization and side effects.

Example: Post-Mount Actions

ts
import { ViewModelBase } from "mobx-view-model";

class ForceAlertVM extends ViewModelBase<{ message: string }> {
  protected didMount() {
    this.rootStore.notifications.push({
      type: 'success',
      title: "May the Force be with you!",
      message: this.payload.message
    });
  }
}

willUnmount(): void protected

Called when the component begins unmounting from the React tree.
Executes before the unmount() method.

unmount(): void | Promise<void> action.bound

Called when the component is unmounted from the React tree.

This method sets isMounted to false.
If you override this method, be sure to call super.unmount(); otherwise your view component connected to this ViewModel will never be unmounted.

didUnmount(): void protected

Called after the view model is fully unmounted.
Ideal for final cleanup operations.

setPayload(payload: Payload): void

Updates the view model's payload data.

The base implementation of this method compares the current payload and the new payload before setting it.
This can be overridden using view models configuration or by overriding the protected isPayloadEqual method.

isPayloadEqual?.(current: Payload, next: Payload): boolean protected

This method is used for comparing the current and next payloads.

You can customize payload comparison overriding this method or configure viewModelsConfig

Example:

ts
class PostcardBox extends ViewModelBase {
  isPayloadEqual() {
    return true;
  }
}

hasChild(vm, deep?): boolean protected

Checks whether the given view model is a child of the current view model.

  • Shallow (deep is false/undefined): vm.parentViewModel === this
  • Deep (deep is true): checks the whole parent chain of vm and returns true if it contains this

Example

ts
class RootVM extends ViewModelBase {}
class ChildVM extends ViewModelBase {}

const root = new RootVM({ id: "root", payload: {} });
const child = new ChildVM({ id: "child", payload: {}, parentViewModel: root });

// inside RootVM
this.hasChild(child) // true
this.hasChild(child, true) // true

hasParent(vm, deep?): boolean protected

Checks whether the given view model is a parent of the current view model.

  • Shallow (deep is false/undefined): this.parentViewModel === vm
  • Deep (deep is true): checks the whole parent chain of this and returns true if it contains vm

Example

ts
class RootVM extends ViewModelBase {}
class ChildVM extends ViewModelBase {}

const root = new RootVM({ id: "root", payload: {} });
const child = new ChildVM({ id: "child", payload: {}, parentViewModel: root });

// inside ChildVM
this.hasParent(root) // true
this.hasParent(root, true) // true

Additional utility types

Reference to source code

InferViewModelParams<T>

Utility type that infers constructor params for a ViewModelBase subclass.
It resolves to ViewModelParams<Payload, ParentViewModel, ComponentProps> based on the class generics.

Example

ts
import {
  ViewModelBase,
  InferViewModelParams,
} from "mobx-view-model";

class UserVM extends ViewModelBase<
  { userId: string },
  null,
  { isAdmin?: boolean }
> {
  constructor(params: InferViewModelParams<UserVM>) {
    params.vmConfig = {
      ...params.vmConfig,
      comparePayload: 'strict',
    };

    super(params);
  }
}

Released under the MIT License.