https://github.com/p-toy-factory/mobx-async-action
MobX asynchronous action.
https://github.com/p-toy-factory/mobx-async-action
mobx
Last synced: 3 months ago
JSON representation
MobX asynchronous action.
- Host: GitHub
- URL: https://github.com/p-toy-factory/mobx-async-action
- Owner: p-toy-factory
- License: mit
- Created: 2023-10-14T06:32:34.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-01-06T05:18:56.000Z (over 1 year ago)
- Last Synced: 2025-01-22T23:41:14.025Z (4 months ago)
- Topics: mobx
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/mobx-async-action
- Size: 50.8 KB
- Stars: 3
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# mobx-async-action
[MobX](https://mobx.js.org) asynchronous action but different with [flow](https://mobx.js.org/api.html#flow).
The reactions won't be triggered until the promise's state changes to be fulfilled or rejected.
## Install
```
npm install mobx-async-action
```## Example
```typescript
import { observable, reaction } from "mobx";
import { expect, test } from "vitest";import { runInAsyncAction } from "mobx-async-action";
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](https://mobx.js.org/api.html#action), but supports asynchronous function.
```typescript
function asyncAction(fn: () => Promise): () => Promise;function asyncAction(
actionName: string,
fn: () => Promise
): () => Promise;
```### runInAsyncAction
Similar to [runInAction](https://mobx.js.org/api.html#runinaction), but use `asyncAction` underhood.
```typescript
function runInAsyncAction(fn: () => Promise): Promise;
```