Mardzis Mardzis - 1 month ago 10
React JSX Question

How to save new state to local json

I have a local JSON file which is used for loading all data to app. In one component 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])
});
}

Answer

You 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 component is loaded it if it's 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 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.