Cadel Watson
Cadel Watson

Reputation: 511

How to include multiple await calls in MobX action

I'm working on an app that requires multiple calls using the await syntax inside a MobX action. A typical example looks like this:

  @action.bound
  async mintToken() {
    const tokenInstance = await this.token.deployed();    
    await tokenInstance.mint(1, { from: this.account });
    await this.updateLastMintedToken();
    await this.updateTokenDetails();
  }

However, this code doesn't seem to execute correctly, due to the way MobX handles actions. According to the docs:

@action only applies to the code block until the first await. And after each await a new asynchronous function is started, so after each await, state modifying code should be wrapped as action.

The example given in the docs uses runAsAction, which I attempted in the following code:

  @action.bound
  async updateLastMintedToken() {
    const tokenInstance = await this.token.deployed();

    runInAction(async function() {
      const result = await tokenInstance.lastTokenMinted.call();
      this.lastTokenMinted = result.toNumber();
    });

  }

Unfortunately this didn't work, because this becomes undefined inside the runInAction call so I can't mutate the state.

Any direction in running multiple async calls in an action is very appreciated!

Upvotes: 1

Views: 1134

Answers (1)

guest271314
guest271314

Reputation: 1

You can use arrow function to set the context within runInAction to the same context as updateLastMintedToken function

  @action.bound
  async updateLastMintedToken() {
    const tokenInstance = await this.token.deployed();

    runInAction(async () => {
      const result = await tokenInstance.lastTokenMinted.call();
      this.lastTokenMinted = result.toNumber();
    });

  }

Upvotes: 2

Related Questions