From d818363c530d233e9e8fc28f08a108ba17cff05b Mon Sep 17 00:00:00 2001 From: Johan Lindskogen Date: Mon, 17 Jan 2022 17:35:28 +0100 Subject: [PATCH] Add setupListeners example for react-native --- docs/rtk-query/api/setupListeners.mdx | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/docs/rtk-query/api/setupListeners.mdx b/docs/rtk-query/api/setupListeners.mdx index 5e9fe04bef..dc52582366 100644 --- a/docs/rtk-query/api/setupListeners.mdx +++ b/docs/rtk-query/api/setupListeners.mdx @@ -77,3 +77,62 @@ If you notice, `onFocus`, `onFocusLost`, `onOffline`, `onOnline` are all actions ```ts title="Manual onFocus event" no-transpile dispatch(api.internalActions.onFocus()) ``` + + +# `setupListeners` for `react-native` + +Uses `@react-native-community/netinfo` for offline detection. + + +```ts title="setupListeners example for react-native" no-transpile +export function setupListenersReactNative( + dispatch: ThunkDispatch, + customHandler?: ( + dispatch: ThunkDispatch, + actions: { + onFocus: typeof onFocus; + onFocusLost: typeof onFocusLost; + onOnline: typeof onOnline; + onOffline: typeof onOffline; + } + ) => () => void +) { + function defaultHandler() { + let unsubscribeOnChange: NativeEventSubscription | undefined; + let unsubscribeOnNetworkStatusChange: NetInfoSubscription | undefined; + + if (!initialized) { + // Handle focus events + unsubscribeOnChange = AppState.addEventListener("change", (state) => { + if (state === "active") { + dispatch(onFocus()); + } else if (state === "background") { + dispatch(onFocusLost()); + } + }); + + // Handle connection events + unsubscribeOnNetworkStatusChange = NetInfo.addEventListener((state) => { + if (state.isConnected) { + dispatch(onOnline()); + } else { + dispatch(onOffline()); + } + }); + initialized = true; + } + + const unsubscribe = () => { + unsubscribeOnChange?.remove(); + unsubscribeOnNetworkStatusChange?.(); + initialized = false; + }; + return unsubscribe; + } + + return customHandler + ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline }) + : defaultHandler(); +} + +```