Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write/edit/overwrite a json file in react native

I know how to read the json file just by importing it

import file from './config/data.json'; console.log(file); .

But is there an easy way to write or edit on it.

like image 322
Damathryx Avatar asked Jun 07 '16 06:06

Damathryx


People also ask

How do I edit an existing JSON file?

Procedure. In the Enterprise Explorer view, right-click your . json file or other file type that contains JSON code and select Open With > JSON Editor. You can compress JSON strings so that the strings display on one line with white space removed between JSON elements.

How do I write a JSON file?

Another way of writing JSON to a file is by using json.dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.


2 Answers

Use AsyncStorage for saving local settings:

The following is to set your settings in your code (This example is for some Switch

async setSettings() {
  try {
    var obj = {};
    var settings = await AsyncStorage.getItem('settings');
    settings = JSON.parse(result);
    Object.assign(obj, settings);
    this.setState(obj);
  }
  catch(e) { }
  finally { }
}

The following is to change your settings in your code

switchChanged(field, value) {
  var obj = {};
  obj[field] = value;
  AsyncStorage.getItem('settings').then(function(strResult) {
    var result = JSON.parse(strResult) || {};
    Object.assign(result, obj);
    AsyncStorage.setItem('settings', JSON.stringify(result));
  });
  this.setState(obj);
}

And finally the call at the render method

<Switch
  onValueChange={(value) => this.switchChanged('reminders', value)}
  value={this.state.reminders} />

Hope it can help you :)

like image 151
Jonathan Stellwag Avatar answered Oct 06 '22 04:10

Jonathan Stellwag


If you absolutely want to read/write files you could use react-native-fs.

If you want to persist application specific settings I would recommend using AsyncStorage.

like image 45
Jean Regisser Avatar answered Oct 06 '22 03:10

Jean Regisser