I have a local JSON file which is used for loading all data to app. In one ponent I load in constructor()
those data. In function addRow()
I add new field but it's just in local state variable. I would like to add it to json file also, so after refresh this new row will be still here.
I was trying find how this solved really easy but I didn't find it. If you know about some 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])
});
}
I have a local JSON file which is used for loading all data to app. In one ponent I load in constructor()
those data. In function addRow()
I add new field but it's just in local state variable. I would like to add it to json file also, so after refresh this new row will be still here.
I was trying find how this solved really easy but I didn't find it. If you know about some 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])
});
}
Share
Improve this question
asked Nov 2, 2016 at 9:38
Martin JindaMartin Jinda
48810 silver badges26 bronze badges
3
- POST request + server side script to write to json file. – dfsq Commented Nov 2, 2016 at 9:54
- Or some javascript (node.js) plugin for react which can work with json – Martin Jinda Commented Nov 2, 2016 at 10:03
- No, you can't write files with just client side code, you need backend for this. – dfsq Commented Nov 2, 2016 at 10:20
2 Answers
Reset to default 4You can't access the file system from the browser for security reasons. If you just want to access it after refreshing, I guess that you could save it in localStorage when you modify the state and then use it when the ponent is loaded it if it's not undefined (you can check this in ponentDidMount). (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
});
}
ponentDidMount(){
let newEmployees = localStorage.employees
if(newEmployees != undefined){
this.setState({
employees: JSON.parse(newEmployees)
});
}
}
If you want to store that JSON persistently and you want more than being able to use it after refreshing, you should do it on the backend. You can also let the user save the file manually (with a download prompt) as it's described here.
There is no way to do it from the client/browser, since they do not have access to file system (form security considerations). You'll to do it on the backend.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744590914a4582599.html
评论列表(0条)