Remembering failed requests and repeating when an internet connection is available
This package is based on a work of jonkofee.
npm install axios localforage # install peer dependencies
npm install @appello/axios-offline
yarn add axios localforage # install peer dependencies
yarn add @appello/axios-offline
import axios, { AxiosAdapter } from 'axios';
import { AxiosOffline } from '@appello/axios-offline';
import NetInfo from '@react-native-community/netinfo';
import LocalForage from 'localforage';
const offlineUrls = ['/list', '/profile'];
export const axiosOfflineInstance = new AxiosOffline({
defaultAdapter: axios.defaults.adapter as AxiosAdapter, // require, basic adapter
storageOptions: {
name: 'axios-offline', // optional, default: "axios-stack"
driver: LocalForage.LOCALSTORAGE, // optional, default: LocalForage.LOCALSTORAGE
},
shouldStoreRequest: config => {
return config.method === 'POST' && offlineUrls.includes(config.url as string);
},
getResponsePlaceholder: config => ({
config,
headers: {},
data: undefined,
status: HttpStatusCode.Ok,
statusText: 'Request successfully stored till back online!',
}),
});
export const Api = axios.create({
adapter: axiosOfflineInstance.adapter,
});
window.addEventListener('online', (event) => {
axiosOfflineInstance.sendRequestsFromStore();
});