mobx-async-action
v0.1.0
Published
MobX asynchronous action
Downloads
3
Readme
mobx-async-action
MobX asynchronous action but different with flow.
The reactions won't be triggered until the promise's state changes to be fulfilled or rejected.
Example
import { observable, reaction } from "mobx";
import { expect, test } from "vitest";
import { runInAsyncAction } from ".";
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
test("runInAsyncAction", async () => {
let hasReacted = false;
const ob = observable({
value: 1,
});
reaction(
() => ob.value,
() => {
hasReacted = true;
}
);
await runInAsyncAction(async () => {
ob.value = 2;
await wait(1000);
expect(hasReacted).toBeFalsy();
});
expect(hasReacted).toBeTruthy();
});
Caveat
If the promise's state never changes, the action may never end.
API Reference
asyncAction
Similar to action, but supports asynchronous function.
function asyncAction<T>(fn: () => Promise<T>): () => Promise<T>;
function asyncAction<T>(
actionName: string,
fn: () => Promise<T>
): () => Promise<T>;
runInAsyncAction
Similar to runInAction, but use asyncAction
underhood.
function runInAsyncAction(fn: () => Promise<void>): Promise<void>;