Skip to main content
Version: v7.0.0

React Native

Hyper Fetch is designed to be environment-agnostic, providing full support for React Native. Its modular architecture allows for easy replacement of core components to seamlessly integrate with native device features.

What you'll learn
  • How to handle online/offline status using NetInfo.
  • How to manage application focus/blur states with AppState.
  • How to re-fetch data when a screen comes into focus.

Online and Offline Status

By default, Hyper Fetch listens to browser-based online/offline events. For React Native, you can use the @react-native-community/netinfo library to track the device's network status.

First, you need to install the library:

npm install --save @react-native-community/netinfo

Then, configure the appManager to use NetInfo for network state detection. This ensures that Hyper Fetch is always aware of the device's connectivity, preventing requests from being sent when the device is offline.

services/client.ts
import { Client } from "@hyper-fetch/core";
import { AppManager } from "@hyper-fetch/react";
import NetInfo from "@react-native-community/netinfo";

import { environment } from "src/environments";
import { ServerErrorType } from "src/types";

export const client = new Client<ServerErrorType>({
url: environment.serverUrl,
appManager: (instance) =>
new AppManager(instance, {
initiallyOnline: NetInfo.fetch().then((state) => !!state.isConnected),
onlineEvent: (setOnline) => {
return NetInfo.addEventListener((state) => {
setOnline(!!state.isConnected);
});
},
}),
});

Application Focus and Blur

To automatically manage requests based on the application's focus state, you can use React Native's AppState API. This allows Hyper Fetch to pause requests when the app is in the background and resume them when it's back in the foreground.

This configuration tells Hyper Fetch to listen for app state changes. When the app becomes active, it's considered focused. When it's inactive or in the background, it's blurred.

services/client.ts
import { AppState, AppStateStatus } from "react-native";
import { Client } from "@hyper-fetch/core";
import { AppManager } from "@hyper-fetch/react";

import { environment } from "src/environments";
import { ServerErrorType } from "src/types";

export const client = new Client<ServerErrorType>({
url: environment.serverUrl,
appManager: (instance) =>
new AppManager(instance, {
focusEvent: (setFocused) => {
const onChange = (status: AppStateStatus) => {
setFocused(status === "active");
};

const subscription = AppState.addEventListener("change", onChange);

return () => subscription.remove();
},
}),
});
That's it!

Your app is now ready to fully use all of the features of Hyper Fetch.