0

I have an issue with MobX as I'd like to call onSortHandler as well as loadingCallback after an async action in my store but the call order is misaligned due to the async action. The added complexity of the issue is that onSortHandler triggers a function which uses a computed value calculated by the given action.

Here is my action in the store:

loadFurniturePage = async (pageNumber: number, pageAmount: number) => {
        const nextPage = await agent.FrontEnd.getNextFurniturePage(pageNumber, pageAmount); <-- I suppose while waiting here, the finally block get called. (See it below)
        nextPage.forEach((furniture: IFurniture) => {
            furniture.type = furniture.typeInString;
            this.furnitureMap.set(furniture.id, furniture)          
        });
    }

Here is the place where I call the action above:

loadFurniturePage(pageNumber, pageAmount).finally(() => { <-- this code block should be called after the action finishes it's running.
    onSortHandler(selectedSortByValue); 
    loadingCallback(false);
});

And this is the computed value I use when calling onSortHandler:

get getAllFurniture() {
    return Array.from(this.furnitureMap.values())
}

Does anybody have an idea, how to solve this?

RPeter7
  • 1
  • 1
  • hi. Is `this.furnitureMap.set(furniture.id, furniture)` an `async` function? – Ehsan Nazeri Oct 06 '21 at 07:40
  • @EhsanNazeri it is not, as far as I know. – RPeter7 Oct 06 '21 at 08:05
  • Does this answer your question? [MobX: Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed](https://stackoverflow.com/questions/64770762/mobx-since-strict-mode-is-enabled-changing-observed-observable-values-withou) – Danila Oct 07 '21 at 09:34

1 Answers1

1

After async function call if you continue to change mobx observables, wrap that code in runInAction

loadFurniturePage = async (pageNumber: number, pageAmount: number) => {
        const nextPage = await agent.FrontEnd.getNextFurniturePage(pageNumber, pageAmount);
        runInAction(()=>{
        nextPage.forEach((furniture: IFurniture) => {
            furniture.type = furniture.typeInString;
            this.furnitureMap.set(furniture.id, furniture)          
        });
})

    }
loadFurniturePage(pageNumber, pageAmount).finally(() => {
    runInAction(()=>{
    onSortHandler(selectedSortByValue); 
    loadingCallback(false);
})

});
Ivan V.
  • 7,593
  • 2
  • 36
  • 53