Published in


Reading data from json files in react native

There are times when we get need to store data for offline purposes in our app.This makes more sense when we need to make articles/stories available to users even when they are offline.In today’s article I am going to show you how to read data from json files in react native along with why I arrived at that decision.

Recently I was developing an app in which I wanted to show stories to users which I published on my blog.My first requirement was that user should be able to view the stories even when they are offline so displaying simple webviews was out of question. Next viable option was to store article data in Asyncstorage and retrieve it for offline purposes but I found that storing and retrieving huge amount of data from Asyncstorage proved to be slowing down my app considerably. Then I thought of adding sublayer between my views and data like redux-persist or realm db for managing data but even that option went down the drain since I had planned to create about 20 topics with 300 stories in each topic.

But I hit the hidden gem in react native when I found that we could import json files directly in react native due to which my work was greatly simplified by simply importing 20 topics jsons in redux initialstate and dispatcing actions for getting relevant stories from topic json files stored directly in react native project.

Now if you are going store sensitive or confidential data then this approach might be wrong but in my case data low latency and app performance was a higher priority and data was anyways freely published.

So in order to import json files in react native here are the following steps:

First create a folder in src where you would like to create your json.I created a dbstore folder.

In order to import json file simply require them in your files as:

Now you can do your processing on json object and pass it around as props.

I usually import json files in initalstate of redux and then pass it as state variable:

You can then call appropriate json files in actions and dispatch the data to the store.

Now I did not have a need to change json data except updating the content so I am planning to use codepush module to update the files when required.Now if you need to order to write back data to json files on click events or some user actions then you can use modules like react-native-fs and select MainBundlePath to write data back to json files.

This might seem a tedious task even when there are client side json dbs available but as I said that I only needed to read the articles so this approach felt right for my use case.

You can follow me on Linkedin or Twitter to have more discussion or ask doubts.

Image source:Pixabay



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store