Amir-Mousavi
Amir-Mousavi

Reputation: 4561

Set local state according to Mobx state

in the component, I want to open a modal according to Mobx state. but I got confused doing that.

in Mobx I have a computed function that returns the report.

@observable report= null;
@computed get getErrorReport(){return this.report}

and in the component, if there is an error I want to open a modal which for that I need to setState the modal flag.

render() { 
    const { getErrorReport } = this.props.myStore!;
    if(getErrorReport) {this.setState({modalOpen:true})}
    .....
}

of course, this update is errorful. generally in these cases that we need setState in render what should be the approach?

Upvotes: 1

Views: 1257

Answers (2)

Shevchenko Viktor
Shevchenko Viktor

Reputation: 5396

you may want to structure your code in such a way.

class MyStore {
    @observable report = null;
    // You do not need a @computed here just to return a property - access it 
    // directly
}


@inject('myStore')  // myStore is an instance of MyStore that you passed to Provider
@observer // observer will trigger a rerender if any observable prop change (report 
          // in your case)
class MyReactComponent extends React.Component {

// so you do not need a set state here 

    render() {
         // Your modal component may differ, this is example
        return (<Modal isOpened={this.props.myStore.report} />)
    }

}

Upvotes: 3

chen ginat
chen ginat

Reputation: 42

according to mobx documentation if you want a variable to trigger your render you should use observable, so it looks like you don't need to use state at all in that case, because observable would trigger render and in your render function you should ask if report is not null and if so just open your modal without changing your state. am i missing something?

Upvotes: -1

Related Questions