Martin Jinda
Martin Jinda

Reputation: 488

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])
    });
}

Upvotes: 5

Views: 6057

Answers (2)

César Landesa
César Landesa

Reputation: 2656

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.

Upvotes: 4

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12872

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.

Upvotes: 0

Related Questions