reactjsreact-jsonschema-forms

Upload default data to a form


Description

I try out the react-jsonschema-form. For my task I would like use default values which the user can upload, such that he doesn't need to fill out the whole form again. I thought the easiest way is to upload some formData as a json which is then inserted in the form.

Steps to Reproduce

  1. Open the js fiddle: https://jsfiddle.net/s056ceq8/33/
  2. Enter a name in the corresponding field.
  3. Submit the data. You will download a hello_world.json file
  4. Upload the hello_world.json file
const Form = JSONSchemaForm.default;

const mySchema = {
  "title": "My Form",
  "description": "My Form",
  "type": "object",
  "required": [
    "name"
  ],
  "properties": {
    "name": {
      "type": "string",
      "title": "Name"
    }
  }
};

class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {
          initialData: props.initialData,
        };
    }

    onChangeUploadData  = e => {
        const fileReader = new FileReader();
        fileReader.readAsText(e.target.files[0], "UTF-8");
        fileReader.fileName = e.target.files[0].name;
        fileReader.onload = e => {
          this.setState({ initialData: e.target.result });
          console.log(this.state.initialData);
        };
    };

    handleSubmit({formData}) {
        var blob = new Blob([JSON.stringify(formData, null, 2)], { type: "application/json;charset=utf-8" });
        saveAs(blob, "hello_world.json");
        console.log(formData);
    }

    render() {
        return (
          <div>
            
            <input label="Upload File" type="file" onChange={this.onChangeUploadData}/>
          <Form schema={mySchema} onSubmit={this.handleSubmit}  formData={this.state.initialData}/>
          </div>
        )
    }
};

ReactDOM.render(<MyForm/>, 
             document.querySelector("#app"));
Expected behavior

If I upload the data the form should update and show the content of the uploaded data.

Actual behavior

I can upload the data and the content of the formData acutally changes. But the form only will have empty fields.


Solution

  • e.target.result gives undefined. you need to Replace e.target.result with JSON.parse(fileReader.result)