javascript – in the component does not display the current state of the store (Mobx) with double destructuring

Question:

There is a mobx store, presented as a class, it has a method for requesting data through the REST API

On the UI, clicking on the button calls this method and sets the loading flag (loadingTestRun) to true, when the request is completed, it is false again, and a loader should be displayed during the processing of the request.

There is a hook that returns the store, the hook works throughout the application and works well. All components interacting with the store are wrapped in useObserve, the problem was found precisely in the component with double destructuring

The problem is that if you access loadingTestRun through rulesStore.loadingTestRun, then everything works out well.

  const { rulesStore } = useStores()

But if I destructurize yet, then in the component where it is expected to see the loading – loadingTestRun remains false when the request is executed

 const { rulesStore : { loadingTestRun } } = useStores()

RootStore example

class RootStore implements IRootStore {
  rulesStore: RulesStore
  groupStore: GroupStore
  projectStore: ProjectStore
  intervalsStore: IntervalsStore
  eventsStore: EventsStore
  templateStore: TemplateStore

  //Сюда подключаем все новые store и передаем в них this
  constructor() {
    this.rulesStore = new RulesStore(this)
    this.groupStore = new GroupStore(this)
    this.projectStore = new ProjectStore(this)
    this.intervalsStore = new IntervalsStore(this)
    this.eventsStore = new EventsStore(this)
    this.templateStore = new TemplateStore(this)
  }
}

class RulesStore implements IRulesStore {
  ...
  loadingTestRun = false
}

Answer:

In my opinion, it all comes down to

var state = {
    rulesStore: {
        loadingTestRun: false,
    },
};
function useStores() {
    return state;
}
function changeState() {
    state.rulesStore.loadingTestRun = true;
}

const { rulesStore } = useStores();
const { rulesStore : { loadingTestRun } } = useStores();
changeState(); 
console.log(rulesStore.loadingTestRun, loadingTestRun);

Neither mobx nor the store implementation has anything to do with it. The state changes asynchronously and this happens later than the assignment.

Scroll to Top