Problem with Expo BackgroundFetch and axios

54 Views Asked by At

I have a problem when executing a task in the background, because the axios instruction does not run if I do not have the APP open, what I try to do is to run the task even if the app is closed but at the time of execution the axios instruction does not run.

As I have my code: First I define my task name

const BACKGROUND_FETCH_TASK = 'event03test';

Then I define the function (the one that carries the instructions from axios, my request to the backend)


const sendlocation = async () => {
  const now = Date.now();
  let date = new Date(now).toISOString();
  const token = await AsyncStorage.getItem('token_access');
  let location = await Location.getCurrentPositionAsync({});
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  };
  if (token && location) {
    axios.post('user/geo/store', {
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      date: date,
      status: 'Online',
    }, {
      headers: headers,
    }).then((res) => {
      let getdata = res.data;
      if (getdata.success) {
      }

    }).catch((err) => {
      console.log(err.response);
    });
  }
}

Then I define the task. In this case I run a console.log to verify that it is running (In development environment with expo metro). but there is where the error is because the call to the console.log is executed when the app is in the background but the function that contains the axios instructions is not.

TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
  const now = Date.now();
  console.log(`Date: ${new Date(now).toISOString()}`);
  await sendlocation();
  return BackgroundFetch.BackgroundFetchResult.NewData;
});

And lastly my background task logging function

async function registerBackgroundFetchAsync() {
  return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
    minimumInterval: 60 * 1, // 15 minutes
    stopOnTerminate: false, // android only,
    startOnBoot: true, // android only
  });
}

I am importing the following expo libraries

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

I want to make my call of the function that contains the axios request to run in the background because it only runs if the app is in the foreground (open), I do not know if it is a permissions problem but looking at the permissions of the app only says that I can get the location in the foreground.

0

There are 0 best solutions below