11

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.