mobx-state-tree
mobx-state-tree copied to clipboard
applyAction with async result
Given an async action (borrowed from https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md#asynchronous-actions-and-middleware)
const Store = types.model({
githubProjects: types.array(types.frozen),
state: types.enumeration("State", ["pending", "done", "error"])
})
.actions(self => ({
fetchProjects: process(function* fetchProjects() { // <- note the star, this a generator function!
self.githubProjects = []
self.state = "pending"
try {
// ... yield can be used in async/await style
self.githubProjects = yield fetchGithubProjectsSomehow()
self.state = "done"
} catch (e) {
// ... including try/catch error handling
console.error("Failed to fetch projects", error)
self.state = "error"
}
})
}))
const store = Store.create({})
// async actions will always return a promise resolving to the returned value
store.fetchProjects().then(() => {
console.log("done")
})
How would one apply this action using applyAction()
and await the result? The signature for apply action is:
export declare function applyAction(target: IStateTreeNode, actions: ISerializedActionCall | ISerializedActionCall[]): void;
It would be nice if it could be made async:
export declare function applyAction<T>(target: IStateTreeNode, actions: ISerializedActionCall | ISerializedActionCall[]): Promise<T>;
Then we can call:
applyAction(store, {name: "fetchProjects"}).then(() => {
console.log("done")
})
Obviously this is a contrived example, but if you have a deeply nested tree it becomes useful.
I think it is a pretty neat idea and is feasible. PRs welcome!
issue moved to : https://github.com/coolsoftwaretyler/mst-middlewares/issues/14
^ Whoops, that's my bad. I gave unclear instructions and this got wrapped up in a project to extract mst middlewares. We are going to keep this open here.
Hey folks, it looks like we had some effort in this regard, but closed a stale PR: https://github.com/mobxjs/mobx-state-tree/pull/857
I'd love to review a new PR against current MST if anyone's interested. But if we don't hear back in a while, I will close this out as well and let it resurface if folks need it.