9

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.

hakkikonu
  • 5,515
  • 6
  • 59
  • 105
Arungopan Gopakumar
  • 155
  • 1
  • 2
  • 10

4 Answers4

5

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

  };
}
Michael Sivolobov
  • 12,034
  • 3
  • 40
  • 63
Ako
  • 165
  • 1
  • 10
  • I'm curious why you get data direct from AsyncStorage in your component instead of checking online status and returning from AsyncStorage or Fetching in your Redux Action. I'm not saying its the wrong way I just don't understand why you'd access state directly in the component... – Patrick Jun 17 '20 at 23:18
  • What do you mean? can you explain more? – Ako Jun 23 '20 at 14:24
4

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
    }
})
Michael Sivolobov
  • 12,034
  • 3
  • 40
  • 63
3

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.

himanshu
  • 433
  • 7
  • 19
0

The easiest way to store offline data is using the AsyncStorage. You can save json or as text. Like

AsyncStorage.setItem('saveitems', JSON.stringify([{id: 1, name: 'test', xyz: ''}]));

To get the Data you can follow below process:

AsyncStorage.getItem('saveitems', (err, result) => {
  console.log(JSON.parse(result));
});

If you want you manage the network connection efficiently .you can use

react-native-offline

Click Here for Explanation

If you want to to study about other storing options you can check below Link.

Click Here