Search code examples
reactjsasynchronousstatemobxmobx-react

The state of the application is not updated instantly in the code via props in React, MobX


If I have such a code

<button onClick = {()=>{
store.increment()
console.log(store.count)
}
}>{store.count}</button>

Then when you click on the button, the counter will be updated, and the counter will already be updated in the console. But if you create a Counter component that will accept the quantity and callback, the state will be asynchronous

<Counter count = {store.count} increment = {store.increment}/>

How can I make sure that the state in the console is already updated. Without the didUpdate method and the update hook if possible

codesandbox https://codesandbox.io/s/mobx-counter-example-forked-v3qcrw?file=/src/index.js


Solution

  • First of all: don't use outdated library versions. Update them to latest.

    Second: change observable api to makeAutoObservable, remove extra actions.

    And third: wrap every component that uses observable values into observer HOC. In your example you wrapped Counter, but Counter actually does not use any observable values, it only gets appState.count as a prop which will be a primitive value when you reference it. And then you pass Counter directly to ReactDOM.render, that won't work.

    I've wrapped it with App component:

    const App = observer(() => {
      return <Counter count={appState.count} increment={appState.incCounter} />;
    });
    

    Here is Codesandbox with working code