Ramesh Rajagopalan
Ramesh Rajagopalan

Reputation: 175

What is the Mobx way to do handle set state with callbacks

I am trying to convert an existing application that uses set state to use Mobx. How can i achieve the set state callback functionality using mobx. Do i need to use componentDidUpdate to achieve this functionality?

Upvotes: 2

Views: 1305

Answers (1)

Tholle
Tholle

Reputation: 112807

You are right in that you need to use componentDidUpdate to do custom logic when the component has been re-rendered with MobX. The observable values will be synchronously updated, but the component will be re-rendered asynchronously as usual.

Example (JSBin)

@observer 
class App extends Component {
  @observable value = ''

  componentDidMount() {
    setTimeout(() => this.value = 'focus', 1000);
  }

  componentDidUpdate() {
    this.ref.focus();
  }

  render() {
    return (
      <input
        ref={ref => this.ref = ref}
        value={this.value}
        onChange={e => this.value = e.target.value}
      />
    );
  }
};

Upvotes: 2

Related Questions