Store data offline and sync once online using React Native and Redux store

Every time i dispatch an action from remote i will save it on AsyncStorage with it's prefred unique name.

Code blow will check connectivity for an android device then dispatch action when connected If we are connected to internet it will dispatch action If not it will get data from AsyncStorage and send to action as a second parameter to store as redux state.

Component that call the action

 // For Android devices
 if (Platform.OS === "android") {
        NetInfo.isConnected.fetch().then(isConnected => {
          if (isConnected) {
            this.props.dispatch(fetchTasks(tok, null));
         }
          else {
            AsyncStorage.getItem("@Your:Data").then(data => {
          if (data !== null) {
            this.props.dispatch(fetchTasks(token, JSON.parse(data)));
          }}}

Action

You can see what am i doing with my second argument data on action.

export default function fetchTasks(token, asyncStorageData) {
  if (asyncStorageData !== null) {
    return function(dispatch) {
      dispatch({
        type: FETCH_TASKS_SUCCESSFUL,
        payload: asyncStorageData
      });
    };
  }
  return function(dispatch) {
    axios
      .get(`${api_endpoint}/your/data`, {
        headers: {
          Token: token
        }
      })
      .then(response => {
        dispatch({ type: FETCH_TASKS_SUCCESSFUL, payload: response.data });
        AsyncStorage.setItem(
          "@Your:Data",
          JSON.stringify(response.data)
        );
      })
      .catch(err => {
        dispatch({ type: FETCH_TASKS_ERROR, payload: err });
      });

  };
}

Persistent storage for redux-store

To store your redux-store in persistent place you can use redux-persist library.

Network status in React Native

To work with network state you should use NetInfo helper class from React Native

To check network status (online/offline):

NetInfo.getConnectionInfo().then(({type}) => {
    switch (type) {
        case 'none':
        case 'unknown':
            // offline status
        default:
            // online status
    }
})

To handle network status change:

NetInfo.addEventListener('connectionChange', ({type}) => {
    switch (type) {
        case 'none':
        case 'unknown':
            // offline statuses, so do nothing
            return
        default:
            // fetch your data here
    }
})

If you want to store large amount of data, you can use react-native-sqlite-storage package as local database.

This will help you store all data which you want to save and when user connect with network fetch all data from database and sync with online database.

For network state you can use NetInfo class of react native.