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
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

Building REST-based React Native Offline Apps

Written by 
Fabio Posada
,
Senior Software Engineer
Building REST-based React Native Offline Apps
blog post background
Recent Posts
Six Ways to Handle Concurrency in the JVM
Is there value in learning Vanilla JavaScript?
How to be efficient in remote design work in multicultural teams

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

Table of contents

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}"></provider>

      <persistgate loading="{null}" persistor="{persistor}"></persistgate>

        <breadprovider></breadprovider>

          <teamsscreen></teamsscreen>

        

      

    

);

}

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></scrollview>

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

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

        
     )}

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

  
    ) : (
      <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

When I was 22 years old, a developer told me,  "Development is not just code, it's an entire world in your head ready to emerge and create amazing things. It's your mark in the world." I abandoned my degree in design for one in systems engineering and I never looked back. As a Software Engineer, I love the fresh challenges and acquired knowledge that each project brings. I thrive on working on projects that matter in people's lives; currently, I'm writing the code to manage Philips's ultrasound technology. I'm most at home using React and other JavaScript frameworks for their ability to seemingly do anything. When I'm not programming, I enjoy playing videogames, watching soccer, and playing with my son.

People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.

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