Reputation: 3685
I am removing decorators from my React Native app (too many issues with babel) and my actions are not working (the contained function does not run).
I'm translating class actions e.g.
class MyStore {
//...
@action
myAction(param) {
//...
}
}
To
class MyStore {
//...
myAction(param) {
action("Perform action with param", (param) => {
//...
})
}
}
What's the correct way to convert a class @action to the non-decorator form?
Upvotes: 4
Views: 1751
Reputation: 102
Why not simply use makeAutoObservable?
import { makeObservable, observable, action } from 'mobx';
class MyStore {
someValue = 0;
constructor() {
makeAutoObservable(this)
myAction(param) {
// Your action code here
this.someValue = param;
}
}
Upvotes: 0
Reputation: 4122
You can define action as
class MyStore {
//...
myAction = action(param => {
//...
});
}
or use runInAction()
class MyStore {
//...
myAction(param) {
runInAction(() => {
//...
})
}
}
Upvotes: 6
Reputation: 31992
What's the correct way to convert a class @action to the non-decorator form?
Decorators evaluate to function calls at runtime, so simply calling them manually would be the most straightforward thing to do. @action
is a method decorator, and method decorators take the following arguments at runtime:
With that in mind, you can simply do:
class MyStore {
myAction(param) {
// ...
}
}
// Apply the @action decorator manually:
action(MyStore.prototype, "myAction");
or:
action(MyStore.prototype, "myAction", Object.getOwnPropertyDescriptor(MyStore.prototype, "myAction"));
If you do this immediately after the class declaration, the result should be completely identical to that by using decorators, without having to use the decorator syntax.
Upvotes: 1