'how to write to a json file in react

I have a json file that I will like to add data into it.

The json file contain:

[{"name":"Flossi","image":"https://robohash.org/istevelitut.png?size=50x50&set=set1","price":49,"info":"Cras dui."},
{"name":"Rab","image":"https://robohash.org/voluptatumsuntiste.png?size=50x50&set=set1","price":64,"info":"Phasellus insi."}]


I tried to use fs but I understand it cannot be done with react. Tried to install this package to npm: https://www.npmjs.com/package/write-json-file

But get an error on the compiling.. Help?



Solution 1:[1]

NodeJS using the built in module fs to read and write and React-Native doesnt have one. I would recommend trying to use react-native-fs, although there are some Android limitations. After following the installation setup, you have to ask yourself where you want to save the JSON. If its in the app internal storage, there's no problem, but if you want to save to external storage there's additional setup that may ultimately just not work (I've experienced this).

import RNFS from 'react-native-fs';
import { Alert, Platform, PermissionsAndroid,} from 'react-native';

const saveFile= (saveLocation,data,encoding='utf8')=> {
  let dataString = JSON.stringify(data,null,2)
  RNFS.writeFile(saveLocation,dataString,encoding)
    .then(()=>Alert.alert('Saved the data!')
    .catch((err)=>Alert.alert("Failed to save data!",err.message)  
}

// you may or may not need this
const getFilePermissionsAndroid = async ()=>{
  const permissions = [
    PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
  ]
  // map permissions to whether or not they are granted
  let checkPermissions = await Promise.all(permissions.map(permission=>
    PermissionsAndroid.check(permission)
  ))
  // filter for ungranted permissions
  let permissionsToRequest = permissions.filter((permission,i)=>!checkPermissions[i])
  // if all are granted theres nothing to do
  if (permissionsToRequest.length == 0)
    return true
  // request the ungranted permissions
  let requestResult = await PermissionsAndroid.requestMultiple(permissionsToRequest);
  // I think requestResult is an array of Booleans but im not sure
  return Array.isArray(requestResult) ?
    // if array return true only if all permissions are granted
    requestResult.every(permission=>Boolean(permission)) :
    requestResult
}

const data = [
  {
    name: "Flossi",
    image: "https://robohash.org/istevelitut.png?size=50x50&set=set1",
    price: 49,
    info: "Cras dui."
  },
  {
    name: "Rab",
    image: "https://robohash.org/voluptatumsuntiste.png?size=50x50&set=set1",
    price: 64,
    info: "Phasellus insi."
  }
];

 
// add some stuff
data.push({
  name:"blah blah",
  image:"https://i.kym-cdn.com/entries/icons/mobile/000/003/406/trap-card-2.jpg",
  price:Math.floor(Math.random()*69),
  info:"Blah blah info"
});

// save to file
if(Platform.OS == 'android'){
  if(!await getFilePermissionsAndroid())
    Alert.alert('Writing to external storage may fail without these permissions','Writes to internal storage should be fine tho');
}
// check out documentation for more paths
let path = RNFS.DocumentDirectoryPath + 'data.json';
saveFile(path,data);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1