Categories
Mobx

State Management with MobX 6 — Do Things When an Observable Meets a Given Condition

Spread the love

MobX is a simple state management solution for JavaScript apps.

In this article, we’ll look at how to use MobX 6 to add state management into our JavaScript apps.

Do Things When an Observable Meets a Given Condition

We can use the when function provided by MobX 6 to do something when the store’s state is in a given condition.

For instance, we can write:

import { makeObservable, observable, computed, action, when } from "mobx";

class Count {
  count = 0;
  get doubleCount() {
    return this.count * 2;
  }
  constructor(count) {
    makeObservable(this, {
      count: observable,
      doubleCount: computed,
      increment: action
    });
    this.count = count;
  }

  increment() {
    this.count++;
  }
}

const store = new Count(1);

when(
  () => store.count === 3,
  () => console.log(`It's 3`)
);

store.increment();
store.increment();

We create a store with the count observable, doubleCount computed state, and the increment action.

Then we instantiate it and assign the returned object to the store .

Next, we call when with a function that returns the condition that we want to look for in the store.

The 2nd callback runs when the condition we return in the function we passed in as the first argument is met.

Since we called increment twice and the store’s count state is initialized to 1, we should see the console log run.

If we don’t pass in a 2nd argument into when , it returns a promise.

So we can use it to wait for a given condition and then run code after that.

For instance, we can write:

import { makeObservable, observable, computed, action, when } from "mobx";

class Count {
  count = 0;
  get doubleCount() {
    return this.count * 2;
  }
  constructor(count) {
    makeObservable(this, {
      count: observable,
      doubleCount: computed,
      increment: action
    });
    this.count = count;
  }

  increment() {
    this.count++;
  }
}

const store = new Count(1);

const when3 = async () => {
  await when(() => store.count === 3);
  console.log(`It's 3`);
};

when3();
store.increment();
store.increment();

We have the same store as in the previous example.

But below that, we have the when3 function that calls when with the same function as before as the first argument.

The 2nd function is omitted.

Then we call the console.log after that.

Then we run the when3 function.

Next, we call increment twice as before.

So we should see the console log run after count reaches 3 as we specified in the when3 function.

Conclusion

We can use the when function provided by MobX 6 to do something after a store’s state meets the condition we’re looking for.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *