mdakovac
mdakovac

Reputation: 61

Tracking state changes in ViewStore of a parent component

I have 2 components: a ParentComponent which renders a ChildComponent

Parent component has a ParentViewStore and child component has ChildViewStore,

Is there a way to track ParentViewStore property changes in ChildViewStore without using React.Component lifecycle methods (e.g. ComponentWillReceiveProps())?

Example code:

class ParentViewStore{
    @observable a;
}

class ChildViewStore{
    /* 
       code to run when 
       ParentViewStore.a 
       changes
    */
}

Code inside the ChildViewStore constructor runs only once, subsequent re-renders do not trigger the constructor again. ParentViewStore is passed as a prop to ChildViewStore

What I've tried:

class ChildViewStore{
    @observable parentProperty;

    constructor(props){
        this.parentProperty = props.parentViewStore.parentProperty
        observe(this.parentProperty, (change) => {
            console.log("change")
        });
    }
}

but this throws [mobx] Cannot obtain administration from [parentPropertyValue]

Upvotes: 1

Views: 204

Answers (1)

Tholle
Tholle

Reputation: 112807

You could use an autorun in the constructor of ChildViewStore to run some custom logic every time a in the ParentViewStore instance is changed.

Example

class ChildViewStore{
    constructor(props){
        autorun(() => {
            console.log(`a changed: ${props.parentViewStore.a}`);
        });
    }
}

Upvotes: 1

Related Questions