Making react native app Offline Ready in 2 mins

Get complete finished shopping cart code here

Today we are going to discuss an amazing feature which will make our app more appealing to users. We will make our app Offline Ready/Friendly in no time. I will continue from the point where we left our last tutorial . We just have to modify 2 of the files and our app will be Offline Ready.

First, we will install the package redux-persist with following command :

npm install redux-persist --save

This package saves last state of our redux store to disk so that app can access data even when offline.

Now, we will make changes to action>>index.js file and our new file will look like this :

import shop from '../api/shop'
import * as types from '../constants/ActionTypes'
 
const request = () => ({
  type: types.REQUEST
})
/*
const response = () => ({
  type: types.RESPONSE
})
*/
const receiveProducts = products => ({
  type: types.RECEIVE_PRODUCTS,
  products: products
})
const receiveCategories = categories => ({
  type: types.RECEIVE_CATEGORIES,
  categories: categories
})
export const getAllProducts = (text="",id="") => dispatch => {
//dispatch(request())
  shop.getProducts(categories => {
   if(categories !== undefined)
    dispatch(receiveCategories(categories))
  }, products => {
   if(products !== undefined)
    dispatch(receiveProducts(products))
 
  },text,id)
}

In the above code, we have commented the request dispatch because we will handle the delay in fetching data with a different logic. Also, we have added conditions that if product or categories are returned undefined when we make api call then there wont be any dispatch. So, if our app is offline and the api call returns undefined then nothing will be injected to the our app redux store.

Next, we will modify index.ios.js/ index.android.js file and our new file will look like this :

import React, { Component } from 'react';
import { AppRegistry,AsyncStorage,Text,View } from 'react-native';
import { createStore, applyMiddleware,compose } from 'redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import reducer from './src/reducers'
import App from './src/containers/App';
import { getAllProducts } from './src/actions'

const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger());
}

const store = compose(applyMiddleware(...middleware),autoRehydrate())(createStore)(reducer)

export default class RNWoo extends Component {
  constructor() {
    super()
    this.state = { rehydrated: false }
  }

  componentWillMount(){
    persistStore(store, {storage: AsyncStorage}, () => {
      this.setState({ rehydrated: true })
    })
    store.dispatch(getAllProducts())
  }

  render() {
    if(!this.state.rehydrated){
      return <Text>Loading...</Text>
    }
    return (
      <Provider store={store}>
       <App/>
     </Provider>
    );
  }
}

AppRegistry.registerComponent('RNWoo', () => RNWoo);

In the above code we have imported persistStore and autoRehydrat from redux-persist and compose from redux . also we are using compose to get initial store value. We are setting the rehydrated state to false so that we can show ‘Loading…’ text before our redux store gets populated/rehydrated with saved data.

So, basically whats happing now is that, first redux store gets injected with data state that was saved last time app was online and if app is able to access internet then it repopulate latest data to store. Even if there is not internet connection the user is able to browse the last content he was able to access last time he was online.

Conclusion

So, offline ready/friendly app lets your user experience your app even without internet. If doesn’t show a blank screen in absence of Internet connection. And now react native has made it even easier to add this feature. Check out the video explanation of this tutorial here :