Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 267
Arungopan Gopakumar Avatar asked Apr 16 '19 04:04

Arungopan Gopakumar


3 Answers

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

  };
}
like image 170
Ako Avatar answered Sep 21 '22 14:09

Ako


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
    }
})
like image 31
Michael Sivolobov Avatar answered Sep 22 '22 14:09

Michael Sivolobov


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.

like image 37
himanshu Avatar answered Sep 19 '22 14:09

himanshu