Forked from intergalacticspacehighway/use-fetch-on-app-foreground.tsx
Created
January 28, 2022 04:25
-
-
Save NileshPatel17/5b9b1c77cbb9df7f647221d3cc15683e to your computer and use it in GitHub Desktop.
app fetch request failing in background
This file contains hidden or 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