Struggling to figure out why my background sync service keeps dying when processing a large batch of message history from the Genesys Cloud API. I am building a React Native app that pulls conversation data in chunks while the app is in the background. Everything works fine for the first few requests, but eventually, the access token expires, and the subsequent API calls fail with a 401.
The issue is that my current refresh logic is too slow or not being awaited correctly before the next request fires, causing the batch job to abort entirely. I am using the standard OAuth2 flow to get the initial token, and I have a refreshToken function that calls /api/v2/oauth/token with grant type refresh_token.
Here is my simplified fetch wrapper:
const fetchData = async (url) => {
let token = await getToken();
try {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});
if (response.status === 401) {
console.log('Token expired, refreshing...');
const newToken = await refreshAccessToken();
// Retry logic here
return fetchData(url); // Recursive retry
}
return response.json();
} catch (error) {
console.error('Fetch failed:', error);
throw error;
}
};
When I run this in a loop for 50+ items, the 401 hits, the refresh happens, but the next recursive call sometimes still uses the old token or the promise chain gets messed up in the background thread. The error I see in the logs is:
“Request failed with status code 401: Unauthorized”
Is there a better pattern for handling token expiration in a high-frequency request loop in React Native? I need to ensure that if multiple requests fail at the same moment, they don’t all trigger separate refresh calls, and that the retry uses the fresh token immediately. Any code examples for a robust retry mechanism with token refresh would be appreciated.