Skip to content

Commit 4b1b7c3

Browse files
committed
added flow
1 parent 72c3fe0 commit 4b1b7c3

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

docs/refguide/api.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,45 @@ Usage:
216216

217217
For one-time-actions `runInAction(name?, fn)` can be used, which is sugar for `action(name, fn)()`.
218218

219+
### Flow
220+
221+
Usage: `flow(function* (args) { })` or `@flow *classMethod`.
222+
`flow()` takes a generator function as its only input
223+
224+
When dealing with _async actions_, the code that executes in the callback is not wrapped by `action`. This means the observable state that you are mutating, will fail the [`enforceActions`](#configure) check. An easy way to retain the action semantics is by wrapping the async function with flow. This will ensure to wrap all your callbacks in `action()`.
225+
226+
Note that the async function must be a _generator_ and you must only _yield_ to promises inside. `flow` gives you back a promise that you can `cancel()` if you want.
227+
228+
```js
229+
import { configure } from 'mobx';
230+
231+
// don't allow state modifications outside actions
232+
configure({enforceActions: true});
233+
234+
class Store {
235+
@observable githubProjects = [];
236+
@observable state = "pending"; // "pending" / "done" / "error"
237+
238+
239+
@flow
240+
*fetchProjects() { // <- note the star, this a generator function!
241+
this.githubProjects = [];
242+
this.state = "pending";
243+
try {
244+
const projects = yield fetchGithubProjectsSomehow(); // yield instead of await
245+
const filteredProjects = somePreprocessing(projects);
246+
247+
// the asynchronous blocks will automatically be wrapped actions
248+
this.state = "done";
249+
this.githubProjects = filteredProjects;
250+
} catch (error) {
251+
this.state = "error";
252+
}
253+
}
254+
}
255+
256+
```
257+
219258
## Reactions & Derivations
220259

221260
*Computed values* are **values** that react automatically to state changes.

0 commit comments

Comments
 (0)