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

Arungopan Gopakumar picture Arungopan Gopakumar · Apr 16, 2019 · Viewed 17.1k times · Source

I am working on a React native application which uses redux for state management. I want to make this application to work offline and persist all the data.

Once the App gets access to network, all the data needs to synced to online database using REST api. Please suggest the best possible ways to approach this scenario, as I am new to REACT NATIVE / Mobile app development.

Help much appreciated.

I have tried to store all the data using AsyncStorage api, but I am finding it difficult manage all the data and not able to figure out how to efficiently sync to online database once the app gets network access.

Answer

Ako picture Ako · Apr 16, 2019

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 });
      });

  };
}