https://codesandbox.io/s/react-mobx-change-value-in-several-components-f2tuu
How to change a variable from different places? The variable is one, but it changes separately in different components and these changes made in one component are not reflected in the other.
App.js
import AppStore from "./AppStore";
import { observer } from "mobx-react";
import SomeComponent from "./SomeComponent";
const store = AppStore();
const App = observer(() => {
return (
<div className="App">
<div>
<i>This is text in App:</i> {store.text}
</div>
<div>
<button
onClick={() => {
store.changeText("This is text from App");
}}
>
Change text from App
</button>
</div>
<SomeComponent />
</div>
);
});
export default App;
SomeComponent.js
import React from "react";
import AppStore from "./AppStore";
import { observer } from "mobx-react";
const store = AppStore();
const SomeComponent = observer((props) => {
return (
<div>
<div>
<i>This is text in component:</i> {store.text}
</div>
<div>
<button
onClick={() => store.changeText("This is text from component")}
>
Change text from component
</button>
</div>
</div>
);
});
export default SomeComponent;
AppStore.js
import { action, makeObservable, observable } from "mobx";
export default function AppStore() {
return makeObservable(
{
text: "Initial text",
changeText(data) {
this.text = data + ": " + new Date().toLocaleTimeString();
}
},
{
text: observable,
changeText: action
}
);
}