0

I'm trying to add some new data to an existing JSON file from text input. I use React Native and I store some data in JSON file called PartyInfo.json, when I fill out a form I want the data will be passed and stored in the PartyInfo.json file.

const PartyInfo = require('../PartyInfo.json');

let party = {
        name: this.state.name,
        info: this.state.info,
        date: this.state.date,
        price: this.state.price,
    };
    let data = JSON.stringify(party);
    PartyInfo.writeFile('PartyInfo.json', data);

I have tried to follow some answers to similar questions but nothing worked... thanks in advance.

2

1 Answer 1

2

You just need to install npm i react-native-fs using npm i react-native-fs and use below code to update your file

 var RNFS = require('react-native-fs');

    var filePath = RNFS.DocumentDirectoryPath + '/YOUR_FILE_NAME';

    RNFS.writeFile(filePath, YOUR_TEXT, 'utf8')
      .then((success) => {
        console.log('SUCCESS');
      })
      .catch((err) => {
        console.log(err.message);
      });
Sign up to request clarification or add additional context in comments.

3 Comments

I have just tried that, it shows me the "Success" message but the input does not append to my JSON file... any ideas?
This is not working.
Make sure you understand where it's writing the file to. Log out the RNFS.DocumentDirectoryPath, if you're testing locally it will be somewhere in the DerivedData folder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.