I work at an application with react native and expo. After I login the user I call an request for getting user data. The app needs to work offline and when the user has connection I make the request and save the date in a sqlite data base. The problem it s the data is big and it blocks the entire app. For fetch I create an hook like this:
import { FetchResponse } from "@/models/Fetch/FetchResponse";
import useRequest from "./useRequest";
import { fetchEndpoints } from "@/models/Fetch/fetchEndpoints";
import { useCallback, useEffect } from "react";
import useTranslation from "./useTranslation";
import { Toast } from "toastify-react-native";
import { useIsConnected } from "./useIsConnected";
import { processItems } from "@/services/processItems";
export const useBackgroundFetch = () => {
const { t } = useTranslation();
const isConnected = useIsConnected();
const { request } = useRequest<FetchResponse>({
url: fetchEndpoints.fetch,
method: "GET",
onSuccess: async (data) => {
const { items } = data;
await processItems(items);
},
});
const makeRequestIfConnected = useCallback(() => {
if (isConnected) {
console.log("Making request");
request();
return;
}
Toast.error(t("info.offlineMode"), "top");
}, [isConnected]);
useEffect(() => {
async function fetchData() {
console.log("Network state: ", isConnected);
// return;
console.log("Registering background fetch");
makeRequestIfConnected();
const interval = setInterval(() => {
makeRequestIfConnected();
}, 1000 * 60 * 15);
return () => clearInterval(interval);
}
fetchData();
}, [isConnected]);
};
the data needs to be updated at a regular time when the user has internet connection. How to optimise this code ?
Thanks!