Reputation: 369
I'm using MobX in React Native and so far I really lite it. Is there some lifecycle or method to call a function when the state in Mobx Store is changed?
Upvotes: 1
Views: 368
Reputation: 112917
You can put an autorun in componentDidMount
and dispose it in componentWillUnmount
:
Example (JSBin)
const store = observable({
data: "data"
});
setTimeout(() => {
store.data += " updated!";
}, 2000);
@observer
class App extends Component {
componentDidMount() {
this.disposer = autorun(() => {
console.log(`Data changed: ${this.props.store.data}`);
});
}
componentWillUnmount() {
this.disposer();
}
render() {
return <h1>{this.props.store.data}</h1>;
}
};
ReactDOM.render(
<App store={store} />,
document.getElementById("app")
);
Upvotes: 0
Reputation: 19059
componentWillReceiveProps
can be used in the component level. For instance, observer container will notify the actual component through props (imaginary use case in TypeScript):
@inject('notificationStore')
@observer
class SomeContainer extends Component<Props> {
...
public render(): JSX.Element {
<Notification
message={this.props.notificationStore.message}
...
/>
}
}
And in Notification:
class Notification extends PureComponent<Props> {
...
public componentWillReceiveProps(nextProps: any): void {
Alert.alert('message', nextProps.message);
}
}
Now, when you mutate notificationStore.message
eg. 'Hello world', it will displayed by Notification component.
If you want more direct approach, then you just inject the component with store and observe the changes. Basically your TypeScript interface should look like this:
interface Props {
notificationStore?: any;
...
}
As you can see, store is always considered as a prop and this means the mutation will trigger componentWillReceiveProps
lifecycle event.
Hope I explained this clear enough.
Upvotes: 1