foxhound87 / mobx-react-form

Reactive MobX Form State Management
https://foxhound87.github.io/mobx-react-form
MIT License
1.09k stars 129 forks source link

Unable to change value if field has nested fields #511

Closed milanbrkic-ms closed 5 years ago

milanbrkic-ms commented 5 years ago

Hi. I have an issues while working with unified nested fields. I have a structure similar to this one

fields: [
  ...
  'resource[].property',
  ...
]

and I initialize form by calling this.form.update method. The biggest problem is that in our app resource[].property could be a string or object with properties.

And when it is a object, next time I want to set new string value nothing happens.

Example:

let field = this.form.$('resource[0].property');

field.value // i.e. { a: 'a', b: {c: 'c'}}
field.set('value', '123')
field.value // i.e. { a: 'a', b: {c: 'c'}}

I saw your comment in this issue https://github.com/foxhound87/mobx-react-form/issues/495#issuecomment-477545938, and get the point that is not possible to set a value, but do you know what could be a solution for my problem? I there a way to remove nested fields and then set value?

I tried to call field.fields.clear() but then field.value === [] and also not possible to set a value that is string.

foxhound87 commented 5 years ago

I think you have to still use update() instead of set() because you are re-creating the fields structure.

milanbrkic-ms commented 5 years ago

How to use update() in order to remove field structure?

foxhound87 commented 5 years ago
const field = this.form.$('resource').$(0);

field.update({
  property: '123',
});

this should work for you, let me know.

milanbrkic-ms commented 5 years ago
const field = this.form.$('resource').$(0);

field.update({
  property: {},
});
console.log(field.value) // ""

This is the solution! In order to remove nested fields we should call update on field with empty object.

I think this feature should go in docs, because it is not intuitive at all..