mobx-state-tree icon indicating copy to clipboard operation
mobx-state-tree copied to clipboard

applyAction with async result

Open mikecann opened this issue 7 years ago • 4 comments

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.

mikecann avatar Oct 09 '17 07:10 mikecann

I think it is a pretty neat idea and is feasible. PRs welcome!

mweststrate avatar Dec 22 '17 14:12 mweststrate

issue moved to : https://github.com/coolsoftwaretyler/mst-middlewares/issues/14

zuhorer avatar Sep 19 '23 18:09 zuhorer

^ 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.

coolsoftwaretyler avatar Sep 21 '23 23:09 coolsoftwaretyler

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.

coolsoftwaretyler avatar Nov 29 '23 05:11 coolsoftwaretyler