Search code examples
javascriptreactjsasynchronousactionmobx-state-tree

Performing asynchronous actions with parameters mobx-state-tree


Using mobx-state-tree I want to pass in parameters to an asynchronous action. They recommend to use generator functions. Their examples does not supply examples using parameters, and I don't find it obvious how to.

I have tried wrapping the flow function inside a normal function to pass the parameters down. However it does not work. I have tried examples below including some additional fiddling.

setAvailability: function (id, status) {
        console.log("inside outer")
        flow(function* () {
            console.log("inside inner")
            try {
                yield UpdateAvailability(id, status)
                const { data } = yield self.fetch(GetTutors)
                self.data = data;
            } catch (e) {
                console.log(e.stack)
            }
        })
    },

setAvailability: flow*(function(id, status) {
            console.log("inside inner")
            try {
                yield UpdateAvailability(id, status)
                const { data } = yield self.fetch(GetTutors)
                self.data = data;
            } catch (e) {
                console.log(e.stack)
            }
        })
    },

When passing parameters inside the flow function it doesn't compile and when I wrap the function it only prints console.log("inside inner")

How can I pass parameters to an asynchronous action function?


Solution

  • I tried a simple example as follows and it works -

    import {flow, types} from "mobx-state-tree"
    
    const Store = types.model({})
        .actions(self => ({
            fetchProjects: flow(function* fetchProjects(par1, par2) { // <- note the star, this a generator function!
                console.log('flow called');
                console.log(par1);
                console.log(par2);
            })
        }));
    
    export const store = Store.create({});
    // async actions will always return a promise resolving to the returned value
    store.fetchProjects('test parameter', 'test parameter 2').then(() => {
        console.log("done")
    });
    

    I think its just the * at the wrong place in your second example.