gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Full example code for file upload #360

Closed sandervanhooft closed 7 years ago

sandervanhooft commented 7 years ago

Version

Tell us which versions you are using:

File should be uploaded using the example code from #112. It however seems to be incomplete. Is there a complete and working example available? This is what @gcanti has included in #112:

var Type = t.struct({
  caption: t.maybe(t.Str),
  copyright: t.maybe(t.Str),
  reference: t.maybe(t.Str),
  file: t.form.File, // <-- your irreducible
  is_video: t.Bool
});

var options = {
  fields: {
    file: {
      type: 'file'
    }
  }
};

var App = React.createClass({

  save() {
    var value = this.refs.form.getValue();
    if (value) {
      console.log(value);
      var fd = new FormData();
      for (var k in value) {
        var v = value[k];
        if (t.form.File.is(v)) {
          fd.append(k, v, v.name);
        } else {
          fd.append(k, v);
        }
      }
      console.log(fd);
      // process form data...
    }
  },

  render() {
    return (
      <div>
        <Form ref="form"
          type={Type}
          options={options}
        />
        <button className="btn btn-primary" onClick={this.save}>Save</button>
      </div>
    );
  }

});

React.render(<App />, document.getElementById('app'));

Actual behaviour

I can't deduce what the new FormData() is or where it should be imported from. Additionally, the for-in loop used in the example throws a guard-for-in esLint warning.

sandervanhooft commented 7 years ago

Ok, just found out that FormData() is a browser function. See here. So the code example was already complete.

Nevertheless, it still yields the ESLint guard-for-in warning. Any thoughts on that?

sandervanhooft commented 7 years ago

Fixed the guard-for-in warning. Simply check within the for-in loop for the value k:

...
for (var k in value) {
  if(k) { // fixes guard-for-in warning from ESLint
    var v = value[k]
    if (t.form.File.is(v)) {
      fd.append(k, v, v.name)
    } else {
      fd.append(k, v)
    }
  }
}
...