'Error fetch when App is put in background

I’m running into an issue with my RN app and was wondering if anyone had come across this and how they solved it. During a fetch call, if the user puts the app in the background and comes back, the fetch always errors out (catch block). Let me know if you have any more questions around this issue.



Solution 1:[1]

Recently fell into this issue. Sometimes network request fails on iOS when app is in background. https://developer.apple.com/forums/thread/106838

You can try below hook which waits for your app to come in foreground before sending requests.

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;
};
// Usage
const fetch = useFetchOnAppForeground();

Gist - https://gist.github.com/intergalacticspacehighway/e1ec053064871f98f50646f80f99c888

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nishan