Please advise how to solve the following problem:
There is a component that outputs some counter:
@observer class MyComponent extends React.Component {
render() {
const data: MyData = new MyData();
return <div>{data['counter']}</div>;
}
}
The counter is stored in a trackable (via mobx @observable) singleton:
export class MyData extends ISingleton
{
@observable data: any = {}
}
At some point the counter (when MyComponent is already created) the counter is set
let data: MyData = new MyData();
data['counter'] = 123;
But MyComponent is not redrawn, although the component seems to track variable change (via mobx @observer and @observable)
Please advise where is the error and how can it be fixed
In mobx you need manipulate the state of observers within actions.
You should extend your singleton to look something like this:
export class MyData extends ISingleton
{
@observable data: any = {}
@action
setCounter(val: number) {
this.data = val
}
}
Then call the setCounter-Method instead of manipulating the state directly.
Please take note that as of version 6 of MobX it is discouraged to use the decorator API (see this for more information).
Every render creates a completely fresh new data
object, effectively resetting it. So you want to store data
at the class instance, not inside the render. Also the data you are modifying is completely different data than the data you are rendering (that is what the new
keyword does). Probably you want to read up a little on how objects, classes & instances work in JavaScript in general