I'm having trouble fetching data using the BackgroundRunner package

I’m currently facing a problem while retrieving data using the BackgroundRunner package.
background.js

let keepAliveInterval;

async function userReady(username) {
const url = https://awsdev.iotcom.io/userready/${username};
try {
const response = await fetch(url, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
});

if (!response.ok) {
  throw new Error(`Server error: ${response.status}`);
}

const data = await response.json();
if (data.message === 'success') {
  console.log('User ready to take call');
  startKeepAlive(username);
} else {
  throw new Error('Unexpected response data');
}

} catch (error) {
console.error(‘Error sending login request:’, error);
}
}

function startKeepAlive(username) {
keepAliveInterval = setInterval(() => {
fetch(‘https://awsdev.iotcom.io/userconnection’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ user: username }),
})
.then((response) => {
if (!response.ok) {
throw new Error(Keep-alive request failed with status ${response.status});
}
})
.catch((error) => console.error(‘Keep-alive error:’, error));
}, 2000);
}

function stopKeepAlive() {
if (keepAliveInterval) {
clearInterval(keepAliveInterval);
console.log(‘Keep-alive stopped’);
}
}

// Register event listeners for BackgroundRunner
BackgroundRunner.on(‘updateUserStatus’, async ({ details }) => {
const { username } = details;
if (username) {
await userReady(username);
}
});

BackgroundRunner.on(‘stopKeepAlive’, () => {
stopKeepAlive();
});

App.js
import { BackgroundRunner } from ‘@capacitor/background-runner’;

useEffect(() => {
if (username) {
console.log(‘Dispatching background event for user:’, username);
BackgroundRunner.dispatchEvent({
label: ‘com.webphone.app.userstatus’,
event: ‘updateUserStatus’,
details: { username },
}).catch((error) => console.error(‘Background task error:’, error));
}

return () => {
  console.log('Stopping keep-alive for user:', username);
  BackgroundRunner.dispatchEvent({
    label: 'com.webphone.app.userstatus',
    event: 'stopKeepAlive',
  }).catch((error) => console.error('Stop keep-alive error:', error));
};

}, [username]);

{
“appId”: “com.webphone.app”,
“appName”: “webphone”,
“webDir”: “build”,
“bundledWebRuntime”: false,
“plugins”: {
“BackgroundRunner”: {
“label”: “com.webphone.app.userstatus”,
“src”: “assets/background.js”,
“event”: “updateUserStatus”,
“repeat”: true,
“autoStart”: true
}
}
}

Please update your post with proper code blocks so we can easily read your code - Extended Syntax | Markdown Guide

1 Like