I've been trying to set up an event listener to get connection changes using the latest version of @react-native-community/netinfo and redux-saga, but I could not make it work. Could you help me?
This code used to work in previously versions:
import { put, take } from "redux-saga/effects";
import { eventChannel } from "redux-saga";
import { NetInfo } from "react-native";
import { OFFLINE, ONLINE } from "redux-offline-queue";
export function* startWatchingNetworkConnectivity() {
const channel = eventChannel(emitter => {
NetInfo.isConnected.addEventListener("connectionChange", emitter);
return () =>
NetInfo.isConnected.removeEventListener("connectionChange", emitter);
});
try {
const isConnected = yield take(channel);
if (isConnected) {
yield put({ type: ONLINE });
} else {
yield put({ type: OFFLINE });
}
} finally {
channel.close();
}
}
Now I have this one:
import { take, put } from 'redux-saga/effects';
import { eventChannel } from 'redux-saga';
import NetInfo from '@react-native-community/netinfo';
import { OFFLINE, ONLINE } from 'redux-offline-queue';
export function* startWatchingNetworkConnectivity() {
const channel = eventChannel(emitter =>
NetInfo.addEventListener(state => state.isConnected)
);
try {
while (true) {
const isConnected = yield take(channel);
if (isConnected) {
yield put({ type: ONLINE })
} else {
yield put({ type: OFFLINE })
}
}
} finally {
channel.close();
}
}
Regards,
Erick