Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add setupListeners example for react-native #1931

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions docs/rtk-query/api/setupListeners.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<any, any, any>,
customHandler?: (
dispatch: ThunkDispatch<any, any, any>,
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();
}

```