Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save intergalacticspacehighway/e1ec053064871f98f50646f80f99c888 to your computer and use it in GitHub Desktop.
Save intergalacticspacehighway/e1ec053064871f98f50646f80f99c888 to your computer and use it in GitHub Desktop.
app fetch request failing in background
import { useEffect, useRef } from "react";
import { AppState, AppStateStatus } from "react-native";
export const useFetchOnAppForeground = () => {
const listener = useRef(null);
function fetchOnAppForeground(params) {
if (AppState.currentState === "active") {
return fetch(params);
} else {
return new Promise((resolve, reject) => {
function fetchData(state: AppStateStatus) {
if (state === "active") {
console.log("calling foreground fetch");
fetch(params).then(resolve).catch(reject);
AppState.removeEventListener("change", fetchData);
listener.current = null;
}
}
AppState.addEventListener("change", fetchData);
listener.current = fetchData;
});
}
}
useEffect(() => {
return () => {
if (listener.current) {
AppState.removeEventListener("change", listener.current);
}
};
}, []);
return fetchOnAppForeground;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment