Hi,
I ran into this problem here.
I have a form and I wanted to set an onClick like this:
~
onClick={this.props.MyModel.handleChange}
~
It took me some time to realize the reason this doesn't work is that an event is not serializable. See here.
Is there any way to make this work?
Thanks,
Eric
Edit: This SO question points to cycle.js, which seems able to stringify circular object and recover them. Could we use something like that to handle event arguments to actions?
Could you post a bit more code? There are 3 possible problems you can run into
handleChange not bound to myModel. This has been fixed in the latest version (0.3.2 or something) onAction handler is attached; as that one cannot serialize functions :)Could you post a bit more code?
Sure :)
~~~jsx
import {types} from 'mobx-state-tree'
cost Email = types.model({
address: '',
handleChange(event) {
this.address = event.target.value.trim();
}
})
~~~
I'm using react-bootstrap, so have a component like this:
~jsx
...
onChange={this.props.Email.handleChange}
...
>
~
This isn't working in v0.2.2 because an event is not serializable. Based on the discussion on gitter, I am hopeful there is an option in v0.3.0 to allow actions to handle events, but don't know how to do that (yet) :blush:
Note that this works as desired:
~jsx
...
onChange={() => {this.props.Email.address = event.target.value.trim();}}
...
>
~
I expected the following to work, but instead it gave a useful error message about events not being serializable:
~jsx
...
onChange={(event) => {this.props.Email.handleChange(event);}}
...
>
~
So my handleChange is being injected properly (and I can console.log it), but it is not working with an event.
I just tried it on v0.3.1 and it still doesn't work out of the box, but maybe there is an option I am missing?
The latest version of MST is less strict about this; it is possible to pass unserialized arguments to actions as long as there is no middleware attached that requires the ability of arguments to be serialized.
That being said, I would strongly suggest keeping your models DOM unaware; in other words, don't process raw event data in models, but outside. That makes testing, server side use etc much easier. E.g:
(event) => {this.props.Email.updateEmail(event.target.value);
E.g:
(event) => {this.props.Email.updateEmail(event.target.value);
Awesome. This is what we ended up doing :)
Thank you.
Most helpful comment
The latest version of MST is less strict about this; it is possible to pass unserialized arguments to actions as long as there is no middleware attached that requires the ability of arguments to be serialized.
That being said, I would strongly suggest keeping your models DOM unaware; in other words, don't process raw event data in models, but outside. That makes testing, server side use etc much easier. E.g:
(event) => {this.props.Email.updateEmail(event.target.value);