How can I store local files such as JSON and then fetch the data from controller?
7 Answers
Since React Native 0.4.3 you can read your local JSON file like this:
const customData = require('./customData.json');
and then access customData like a normal JS object.
-
Is this syntax still supported ? because i can't use this syntax in my code. May 23, 2016 at 8:23
-
1Seems to work with React Native 0.26.2 for iOS. You might want to check with
react-native -v
and try reading thepackage.json
.– peterMay 26, 2016 at 7:21 -
1customData only storing first 3500 character of file customData.json, Any other way to load large file @peter– AkkiFeb 11, 2017 at 9:52
-
-
ES6/ES2015 version:
import customData from './customData.json';
-
-
3@farmcommand2 It can be any name.
import myJsonFile from './foobar.json';
– PaulMestJul 28, 2017 at 0:25 -
1I just tried with React Native 0.57, and looks like the .json extension is not necessary. Feb 15, 2019 at 20:49
-
1@ManuelZapata That is correct. If you exclude the suffix, the module resolver will try different extensions until it finds one that works. More info here: nodejs.org/api/modules.html#modules_all_together– PaulMestFeb 17, 2019 at 20:50
For ES6/ES2015 you can import directly like:
// example.json
{
"name": "testing"
}
// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
If you use typescript, you may declare json module like:
// tying.d.ts
declare module "*.json" {
const value: any;
export default value;
}
The following ways to fetch local JSON file-
ES6 version:
import customData from './customData.json';
or import customData from './customData';
If it's inside .js
file instead of .json
then import like -
import { customData } from './customData';
for more clarification/understanding refer example - Live working demo
maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...
Take a look at this Github issue:
https://github.com/facebook/react-native/issues/231
They are trying to require
non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.