Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mobx react action binding

For those who has written apps with mobx + react, I'm wondering if there's a better way to handle context issue (eg. this. returns undefined in mobx store) when using onClick event handler inside a react component w/ inject & observer.

I have been writing the handler like onClick={actionFromStore.bind(this.props.theStore)} to resolve that issue, but it seems like there should be more concise way to do this that I'm not aware of.

I'm not a mobx expert, any advice would be appreciated!

The actions here are async fetch requests

like image 819
Bi Yoo Avatar asked Jan 10 '19 04:01

Bi Yoo


1 Answers

You can either use @action.bound decorator:

@action.bound
doSomething(){

    // logic

}

or use labmda function which will preserve the context:

@action
doSomething = ()=> {

    // logic

}
like image 168
Nir Weber Avatar answered Nov 15 '22 05:11

Nir Weber