Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX async reaction

Hi I'm using MobX in a store and I need to have an async reaction when a computed value has changed:

class Store {
    @observable user;
    @observable something;

    @computed get firstParam () {
         return this.user && this.user.params[0];
    }

    async loadSomething () {
        reaction(
                () => this.firstParam,
                async (param) => {
                    const { data: something } = await axios.get(`url/${param}`);

                    runInAction('update state after fetching something', () => {
                        this.something = something;
                    });
                }
            );
     }

}

I was wondering what would be the difference here with using when instead of reaction apart from the running condition ?

when(
    () => !!this.firstParam,
    async () => {
         // fetch using this.firstParam
    }
)
like image 296
Komo Avatar asked Aug 19 '16 10:08

Komo


2 Answers

Note that when executes it's effect only once and then stops. So in your case the data would only be fetched once.

like image 154
mweststrate Avatar answered Nov 18 '22 13:11

mweststrate


        reaction(
            () => this.firstParam,
            async (param) => {
                const { data: something } = await axios.get(`url/${param}`);

                runInAction('update state after fetching something', () => {
                    this.something = something;
                });
            }
        );

This will track just this.firstParam and when that return a new data it will call

            async (param) => {
            const { data: something } = await axios.get(`url/${param}`);

            runInAction('update state after fetching something', () => {
                this.something = something;
            });

Now, If you go with when I believe it would end up doing the same, Taken from mobx docs:

You can use observable data structures as a promise... After completing the asynchronous action, just update your data

So i see no reason why not to use when in your case.

like image 22
Sagi Medina Avatar answered Nov 18 '22 15:11

Sagi Medina