FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Upgrade

Building REST-based React Native Offline Apps

Written by 
Fabio Posada
,
Senior Software Engineer
Building REST-based React Native Offline Apps
blog post background
React Developer Salaries
Comparing Hourly Rates Between Software Consultancies
React Native App Of The Week: Speedy Cash
Building REST-based React Native Offline Apps
Speed, Quality, Price: Choose Two When Building Custom Software
Remote Usability Testing

“We can only see a short distance ahead, but we can see plenty there that needs to be done” – Alan Turing

Introduction

Do not underestimate the importance of UX/UI when developing a mobile app. It’s a good idea to visualize different environments where it may be used (on a plane, in a subway, at a train station, at home, etc.) and their respective variables. One of the most important environments that developers and designers often overlook is whether the user is connected to the internet or not.

Twitter does a good job giving the user visual feedback that they’re not connected to the internet.

Twitter

Facebook handles this in different ways depending on the situation. For the “Watch” tab, it shows us something is wrong and that we need to try again.

Facebook

One method to ensure your app properly handles poor or no connection situations is to develop with an “offline first” approach. Below we will explore the “offline first” approach using various tools in React Native.

Why “offline first?”

Years ago, a teacher once told me “everyone needs to know how to sell more.” In our case, we have a product and a consumer. To gain user trust (and sell more) we need to improve UX in the mobile app. Developing with an “offline first” approach measurably improves the UX of an application, which means we will gain more trust from our users.

What do I need to know before getting started?

Use local data whenever possible

In social networking apps, you can continue reading posts without an internet connection because the apps fetch more posts than you’re looking at and stores them in the app locally. When you replace it with new information it’s best to flush the old from storage.

Adapt your layout

It's good practice to use “skeletons” for the UI. A good example of this is the Marketplace tab on Facebook. Notice how the skeleton first appears before the content is loaded:

Facebook

Separate UI from data

In the skeleton example, it’s also good practice to isolate the interface from its data. This way you can load the skeleton and make requests for media behind the scenes.

Inform the user but don’t be direct and aggressive

It’s bad practice, however, to bombard people with a lot of pop-up messages. Try to find another way whenever possible. Remember, it’s not what you are saying, but how you say it.

 pop-up message

Act as if nothing is wrong

A regular network connection is something that should not be depended upon, so try to design your app with that in mind. Let the user interact as much as possible before you have to inform them they are offline.

Cache problems?

Procure the critical data you need for customer engagement and use it for as long as possible. A good idea is to create a PIN generator for authentication flows, storing it in a secure place and using it in case something goes wrong. 

Data protection

You can store whatever you need but assume that someone else is going to try to read it. Therefore make sure this information is encrypted, readable only by you (or your company).

Tools / Packages

Redux persist

Redux persist allows you to persist data and configure blacklists and whitelists. This library uses AsyncStorage as a dependency. Check out the Redux Persist docs.

Middleware 

This library helps you handle network connections and integrates well with Redux. It is also a dependency of @react-native-community/netinfo. Check out their Github repo

Redux/REST API

There are two main strategies to manage React Native offline apps: REST-based and GraphQL-based.

In this post, however, we’re only going to cover REST-based apps.

Caching Libraries
Taken from “React Advanced, London” conference

EXAMPLE CODE

We’re going to fetch data from an API and render it on the screen. The data comes from https://www.football-data.org/

Let’s start creating a simple reducer:

	
export default function teamsReducer(state = {}, action: any) {
  switch (action.type) {
    case "FETCH_TEAMS_START":
      return {
        items: [],
        loading: true,
        isError: false,
      };
    case "FETCH_TEAMS_SUCCESS":
      return {
        items: action.data,
        loading: false,
        isError: false,
      };

    case "FETCH_TEAMS_FAILURE":
      return {
        items: [],
        loading: false,
        isError: true,
        errorMessage: action.errorMessage
    };
    default:
      return state;
  }
}
	

And now combine the reducers and export:

	
import {combineReducers} from 'redux';
import teams from './teams';

const rootReducer = combineReducers({
    teams,
});

export default rootReducer;
	


export default rootReducer;

Ok, now it’s time for setting redux + thunk:

	
import {AsyncStorage} from 'react-native';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './src/reducers';
const composeEnhancers = __DEV__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose : compose;

export default (initialState= {}) => {
  const middlewares = [thunk];
  const store = createStore(rootReducer,
    initialState,
    composeEnhancers(applyMiddleware(...middlewares)),
  );

  return {store };
};
	

At this point, we have the basic redux and thunk configuration but we need to integrate two different libraries: “redux-persist” and “react-native-offline.”

Setting redux-persist

	
import {AsyncStorage} from 'react-native';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './src/reducers';
import { persistStore, persistReducer,  } from 'redux-persist'

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default (initialState= {}) => {
  const middlewares = [thunk];
  const store = createStore(persistedReducer,
    initialState,
    composeEnhancers(applyMiddleware(...middlewares)),
  );
  let persistor = persistStore(store)

  return {store, persistor};
};
	

We set the persistence to store both the reducers and the configuration object. We are not giving redux-persist whitelists or blacklists, so as default it will persist all reducers.

Setting up react-native-offline reducer

For setting react-native-offline we’re going to include the reducer that the API provides us.

	
import {combineReducers} from 'redux';
import { reducer as network } from 'react-native-offline';

import teams from './teams';

const rootReducer = combineReducers({
    teams,
    network
});

export default rootReducer;
	

Store, Persistor, and PersistGate:

Import PersistGate from “redux-persist” to bundle the app, store, and persistor:

-- CODE language-jsx keep-markup --
import { PersistGate } from "redux-persist/integration/react";
import configureStore from "./store";
const { store, persistor } = configureStore();export default function App() {
  return (
    <Provider store={store}>

      <PersistGate loading={null} persistor={persistor}>

        <BreadProvider>

          <TeamsScreen />

        </BreadProvider>

      </PersistGate>

    </Provider>

);

}

Now that we have access to react-offline-reducer, we just need to map it to the screen:

-- CODE language-jsx keep-markup --
function mapDispatchToProps(dispatch: any) {
   return {
       actions: bindActionCreators(actions, dispatch),
   };

}

export default connect(mapStateToProps, mapDispatchToProps)(TeamsScreen);

Once mapped we can use it and modify the screen according to the behavior we want, for example:

-- CODE language-jsx keep-markup --
{
  props.network.isConnected ? (
   <ScrollView>

     {props.teams.items && (
        <Subtitle type={1} style={styles.subtitle}>

          Total football teams: {props.teams.items.length}

        </Subtitle>
     )}

     {props.teams &&
        props.teams.items &&
        props.teams.items.map((team: ITeam) => (
        <Team key={team.id} item={team} />
    ))}

  </ScrollView>
    ) : (
      <Text>Hmmm, something is wrong with your internet connection</Text>
    );
}

Conclusion

Offline design is a crucial component of improving both UX and customer satisfaction, ultimately leading to more sales.

Be optimistic in your UI and pessimistic in the request

Developer Adrien Thiery said you need to trust more in your UI and less in your request, and I agree. It’s a good idea to assume the network won't always be available. Check out this video on Offline First Applications on Youtube for more information.

Layout

A layout designed for offline handling keeps the user engaged while the app is working behind the scenes.

Store and Cache

Storing and caching data is a great technique for mobile apps. You can improve its performance, network usage, and the UX, all at the same time.

Fabio Posada
Written by
Fabio Posada
Fabio Posada

As a Senior Software Engineer at FullStack Labs, my responsibilities involve creating and delivering mobile applications that help people in their lives. I have over 7 years of experience in software development, solving problems through technologies like JavaScript, .Net and Python and with a huge knowledge about frameworks in these technologies. My passions are my family, software development and pc games!

FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects start at $50,000.

company name
name
email
phone
Type of project
Reason for contact
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.