4

I'm trying to create a form in react which will update a JSON file with the values in the form upon submit. (The endgame is that this will create an array of data in the JSON file each time the form is submitted which can then be used to populate a "list" of the submitted results elsewhere in the app)

The form itself works OK but every time I press submit I get the error: "TypeError: fs.writeFile is not a function"

import React, { Component } from "react";
import { Form, Button } from 'semantic-ui-react';
import jsonfile from'jsonfile';

var file = 'data.json'

var obj = {name: 'JP'}


export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      name: "",
      email: ""
    }

    this.handleChange = this.handleChange.bind(this);
    this.sendDataSomewhere = this.sendDataSomewhere.bind(this);
}


handleChange = (e, {name, value}) => {
  this.setState({[name]: value})
}

sendDataSomewhere = function jsonfile(file){
jsonfile.writeFile(file, obj, function (err) {
  console.error(err);
});
};

  render() {
    return (
     <div>
      <Form onSubmit={this.sendDataSomewhere}>
        <Form.Field>
          <Form.Input name="name" value={this.state.name} onChange={this.handleChange}/>
        </Form.Field>
        <Form.Field>
          <Form.Input name="email" value={this.state.email} onChange={this.handleChange}/>
        </Form.Field>
        <Button type="submit">Submit</Button>
       </Form>
     </div>
    );
  }
}

If anyone could let me know what I'm doing wrong or provide an example of something similar I would greatly appreciate it.

Thanks

1
  • Could you update your sendDataSomewhere function? Seem you typed it uncorrect. Commented Aug 29, 2017 at 14:29

4 Answers 4

9

Client-side solution is:

const handleSaveToPC = (jsonData,filename) => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = `${filename}.json`;
  link.href = url;
  link.click();
}
Sign up to request clarification or add additional context in comments.

Comments

4

FS is not accessible in the client

This is not possible to write to a file in the client.

You must submit to an endpoint, for example a Node server. There you can use the node module fs. This will let you write the data to a file.

The reason it is not possible to write to a file in the client is because of security reasons.

Alternate solution

If you need to aggregate post data over time you can do a couple of things in react. First, you can use a state management system, like Redux or the context api and hooks. That will keep your data as you move throughout the app. You will lose data if you hard refresh though.

The second step is to add local storage and a way to "Hydrate" your app. That way the data will be safe until the app cache is removed.

This solution is much more preferable to writing Blobs and downloading them in the client.

3 Comments

Thanks for responding. I'm fairly new to javascript so I'm not really familiar with the concept of submitting to an endpoint. Would you happen to know if there was an example/tutorial anywhere I could take a look at?
look at starting express this will show you how to setup a server and make some end points. Then you will add logic to an endpoint to write a response to a json file on the server. You will also have to look at how to post from recat this question will help you get the basics of that. Good Luck
That's great. Thank you.
2

This seems to work offline. you can use chrome F12 and go offline or use windows airplane mode and this still saves. probably a bit different that all you desire, but take a look at it.

https://www.npmjs.com/package/filesaver.js-npm

Comments

0

Writing form values to JSON files can not be done directly in react, rather create a tiny API to do the job.

Let's say your form values object as JSON looks as below;

const formObject = {
    "name":"arif updated",
    "surname":"shariati updated"
}

Now you can write to your file. If file does not exist, it will create one. If already exists, it will overwrite.

fs.writeFile('./myJSON.json', JSON.stringify(formObject), (err) => {
        if (err) console.log('Error writing file:', err);
    })
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.