Forked from intergalacticspacehighway/use-fetch-on-app-foreground.tsx
Created
February 28, 2023 11:31
-
-
Save mtzfactory/b016975b8985fff80069f5a4dec5284f to your computer and use it in GitHub Desktop.
app fetch request failing in background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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