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;
}
);
}
2
Answers
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
When an app is put into background mode, its resources and network connections may be restricted or terminated by the operating system. This can cause a fetch() call to fail if it is actively running when the app is put into the background.
In React Native, this behavior can be controlled through the use of App State events. When the app is put into the background, the AppState module will emit an event with a value of ‘background’, which can be used to pause or cancel any active network connections or background tasks.
To prevent fetch() calls from failing when the app is put into the background, you can do the following:
By handling AppState events in this way, you can ensure that your app’s network connections and resources are properly managed when it is put into the background, reducing the likelihood of fetch() calls failing.