How to save new state in local json

I have a local JSON file that is used to load all the data into the application. In one component, I load this data into constructor() . In the addRow() function, I add a new field, but it is just in the local state variable. I would also like to add it to the json file, so after the update this new line will be here.

I tried to find how to solve this very easily, but I did not find it. If you know about a topic, send it to me.

 constructor() { super(); this.state = { employees: require('json!../../../data/employees.json') }; this.addEmployee = this.addEmployee.bind(this); } addEmployee(employee) { this.setState({ employees: this.state.employees.concat([employee]) }); } 
+5
source share
2 answers

You cannot access the file system from a browser for security reasons. If you just want to access it after it is refreshing, I think you can save it in LocalStorage when the state changes, and then use it when the component is loaded, if it is not undefined (you can check this in componentDidMount ) (The code below is not tested)

 addEmployee(employee) { let newEmployees = this.state.employees.concat([employee]) localStorage.setItem('employees', JSON.stringify(newEmployees)); this.setState({ employees: newEmployees }); } componentDidMount(){ let newEmployees = localStorage.employees if(newEmployees != undefined){ this.setState({ employees: JSON.parse(newEmployees) }); } } 

If you want to keep this JSON persistently, and you want more than being able to use it after the upgrade, you have to do it on the backend. You can also allow the user to save the file manually (with a download prompt), as described here .

+3
source

It is not possible to do this from the client / browser because they do not have access to the file system (form security considerations). You will do it on the backend.

0
source

Source: https://habr.com/ru/post/1259147/


All Articles