@tanstack/offline-transactions
Version:
Offline-first transaction capabilities for TanStack DB
90 lines (89 loc) • 2.29 kB
JavaScript
import NetInfo from "@react-native-community/netinfo";
import { AppState } from "react-native";
class ReactNativeOnlineDetector {
constructor() {
this.listeners = /* @__PURE__ */ new Set();
this.netInfoUnsubscribe = null;
this.appStateSubscription = null;
this.isListening = false;
this.wasConnected = true;
this.handleAppStateChange = (nextState) => {
if (nextState === `active`) {
this.notifyListeners();
}
};
this.startListening();
}
startListening() {
if (this.isListening) {
return;
}
this.isListening = true;
if (typeof NetInfo.fetch === `function`) {
void NetInfo.fetch().then((state) => {
this.wasConnected = this.toConnectivityState(state);
}).catch(() => {
});
}
this.netInfoUnsubscribe = NetInfo.addEventListener((state) => {
const isConnected = this.toConnectivityState(state);
if (isConnected && !this.wasConnected) {
this.notifyListeners();
}
this.wasConnected = isConnected;
});
this.appStateSubscription = AppState.addEventListener(
`change`,
this.handleAppStateChange
);
}
stopListening() {
if (!this.isListening) {
return;
}
this.isListening = false;
if (this.netInfoUnsubscribe) {
this.netInfoUnsubscribe();
this.netInfoUnsubscribe = null;
}
if (this.appStateSubscription) {
this.appStateSubscription.remove();
this.appStateSubscription = null;
}
}
notifyListeners() {
for (const listener of this.listeners) {
try {
listener();
} catch (error) {
console.warn(`ReactNativeOnlineDetector listener error:`, error);
}
}
}
subscribe(callback) {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
if (this.listeners.size === 0) {
this.stopListening();
}
};
}
notifyOnline() {
this.notifyListeners();
}
isOnline() {
return this.wasConnected;
}
dispose() {
this.stopListening();
this.listeners.clear();
}
toConnectivityState(state) {
return !!state.isConnected && state.isInternetReachable !== false;
}
}
export {
ReactNativeOnlineDetector
};
//# sourceMappingURL=ReactNativeOnlineDetector.js.map