2

I have tried almost any example provided in docs but I can't run it. I want to make a request to a specific url with axios (or fetch method) every 60 seconds and process the data in the background. In other words I want something common like:

this.getPageInterval = setInterval(() => {
    const json = await (await fetch(this.fetchURL)).json();
    ...// etc

}, 60000)

can happen when the app is in background.

my console.log says 'task registered' but it feels like this block of code never triggers(global scope):

BackgroundFetch.setMinimumIntervalAsync(5);
const taskName = 'test-background-fetch';
TaskManager.defineTask(taskName, async () => {
    console.log('background fetch running');
    try {
        const receivedNewData = await (await fetch(this.fetchUri)).json();
        console.log('receivedNewData', receivedNewData) 
        return receivedNewData ? BackgroundFetch.Result.NewData : BackgroundFetch.Result.NoData;

        let isRegistered = await TaskManager.isTaskRegisteredAsync(taskName);
        console.log("isRegistered: ", isRegistered);

    } catch (error) {
        return BackgroundFetch.Result.Failed;
    }
    console.log("BackgroundFetch.Result.NewData", BackgroundFetch.Result.NewData);
    return BackgroundFetch.Result.NewData;
});

and in my class component:

await BackgroundFetch.registerTaskAsync(taskName, {
        setMinimumIntervalAsync: 5,
        stopOnTerminate: false
    });
    await BackgroundFetch.setMinimumIntervalAsync(5);
    alert('task registered');
    console.log('task registered');
sina farbod
  • 497
  • 4
  • 17

1 Answers1

0

It seems you're not registering your task in your class component. Is taskname defined as 'test-background-fetch' in your component? You need to call exactly the same task name.

Also some phones are somewhat problematic with background tasks. I never tried it on expo, but on React Native some brands had to go through some extra setup.

Also note that in the documentation it says it only works when backgrounded. Terminated apps wont run the background function.

Thales Kenne
  • 2,705
  • 1
  • 12
  • 26