Created
January 28, 2022 04:10
-
-
Save intergalacticspacehighway/e1ec053064871f98f50646f80f99c888 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