-
I am trying to connect my proxy class with MobX. My use case is that I need to validate/convert the value before it's added to object. However, when I run my code, set trap is never called. Obviously, the value is changing correctly but I need to covert the case for example when the user assigns a string and that string should be converted to a number in set trap. Is there any way to make it work with MobX. Any help is appreciated. Thanks a lot. :) import React from "react";
import { observer } from "mobx-react-lite";
import { observable, extendObservable, configure } from "mobx";
configure({ enforceActions: false }); // strict mode
class Store {
constructor() {
this.params = observable(
new Proxy(
{},
{
set: (object, key, value) => {
alert("set: ", key, value);
// validate and convert value <==============
object[key] = value;
return true;
},
get: (object, key) => {
console.log("get: ", key);
if (typeof object[key] === "function")
return (...args) => Reflect.apply(object[key], object, args);
return object[key];
}
}
)
);
extendObservable(this.params, { value: 0 });
}
}
const store = new Store();
const App = observer(() => (
<>
<div>Value: {store.params.value}</div>
<button onClick={() => (store.params.value++)}>increment</button>
</>
));
export default App; Codesandbox here |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You have to do it other way around |
Beta Was this translation helpful? Give feedback.
You have to do it other way around
this.params = new Proxy(observable({}))
Calling
extendObservable
on proxy could be a bit tricky, not sure.If I may suggest, don't use proxy for this, keep validation inside action that adds the value to the object.