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