1

I am using fetch to perform an API call on React Native but as soon as the app is put in the background, the request fails/is cancelled. How can I let the request finish?

Edit: I have tried to add the 'Background processing' background mode capability in xcode and that didn't help.

Edit 2: I tried switching to axios for the request and that didnt help.

export const performAPICall = async (endpoint, body) => {
const backendURL = "https://example.com/api";

return await axios.post(backendURL+'/'+endpoint, body, {
    headers: {
        'Content-Type': 'application/json',
        "Authorization": "Bearer "+store.getState().nav.accessToken
    }
})
.then((res) => res.text())
.then(
    (result) => {
        result = JSON.parse(result);
        return result;
    },
    (error) => { // <--- This is where it hits when starting an API call then putting the app in the background
        // [AxiosError: Network Error] is the error
        console.log("performAPICall error", error); 
        return null;
    }
)
.catch(
    (error) => {
        console.log("API CALL CATCH", error);
        return null;
    }
);

}

Adam B
  • 95
  • 11
  • This may help: https://stackoverflow.com/questions/35376690/how-can-i-run-background-tasks-in-react-native – trndjc Apr 14 '23 at 19:59
  • @trndjc That seems to speak specifically about background tasks and not tasks that started before going into the background. – Adam B Apr 18 '23 at 17:19
  • is it really necessary to make this api call in the background? I think a better approach would be to stall it while in background and make it again when app becomes active using AppState – YaNuSH Apr 21 '23 at 07:06
  • @AdamB are u able to solve this? im having the same issue when fetch request is send and user switch to another app causing the react native app pushed to background and request failed. btw only occur on ios physical device though, i cant reproduce on simulator.. – Annie Tan Jun 13 '23 at 16:24

1 Answers1

0

Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music etc you can check this React native official doc for furthur information

https://reactnative.dev/docs/headless-js-android

also you can refer this

react native background API calls on iOS

Sweety SK
  • 351
  • 1
  • 10