Seeking assistance with my React Native app: I am trying to make an API call 30 seconds after the app goes into the background. I am using AppState from react-native to detect when the app goes into the background, but I'm not receiving any callback after the 30-second timeout set with setTimeOut(). Can anyone offer guidance on what I might be missing? Below is the code snippet I have tried so far:
useEffect(() => {
let backgroundTimer;
const handleAppStateChange = (nextAppState) => {
if (nextAppState === 'background') {console.log("your app goes to the background")
backgroundTimer = setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log('API Response:', data))
.catch(error => console.error('API Error:', error));
}, 30000);
} else {
clearTimeout(backgroundTimer);
}
};
AppState.addEventListener('change', handleAppStateChange);
return () => {
AppState.removeEventListener('change', handleAppStateChange);
clearTimeout(backgroundTimer);
};
}, []);