Is it possible to sync data in background React Native?

I’m struggling with a functionality in my app since few weeks.

I will explain my project ; I have a react native app, that connect multiples user. A user can create an event, like a meeting, and the other user get a notification. The event is added in the native calendar of the user who created the meeting (let’s call him user 1), and I want to add it also in the user who is invited to the meeting (let’s call him user 2). My functionality to sync events in the native calendar for the user 2 is working fine, when the user open the app, or the app state change. But I want to sync the native calendar of user 2 even if he not open the app, like in background.

So for that, I’ve two solution in my mind. The best one is the notifications. So when the user 1 create a meeting, user 2 always get a notification and my idea is when the notification is shown, I can sync the calendar. So for notifications, I use firebase, and the notifications are shown in background, but my code is not executed. The problem is that I’ve some error with my code running background messages. My error say that I run multiple HeadlessTask with the id ReactNativeFirebaseMessagingHeadlessTask. I don’t know why I get this error, but i still have the background notification, but not with the console.log(). So I give up this idea with the notifications.

Here is my code to register background notifications :

import * as React from 'react';
import { useState, useEffect } from 'react';

import { API_KEY, PROJECT_ID, STORAGE_BUCKET, MESSAGING_SENDER_ID, APP_ID } from '@env';

import firebase from '@react-native-firebase/app';
import messaging from '@react-native-firebase/messaging';
import { AppRegistry } from 'react-native';

import { syncCalendarEventId } from '../utils/calendarSync';

const register = async () => {
    const firebaseConfig = {
      apiKey: `${API_KEY}`,
      projectId: `${PROJECT_ID}`,
      storageBucket: `${STORAGE_BUCKET}`,
      messagingSenderId: `${MESSAGING_SENDER_ID}`,
      appId: `${APP_ID}`,
      // databaseURL: '...',
      // authDomain: '...',
    };

    firebase
    .initializeApp(firebaseConfig)
    .then(() => {
        registerBackgroundMessage();
    })
    .catch(error => {
    });
};

export async function initializeNotifications() {
    await register();

    if (!firebase.apps.length) {
        register();
    } else {
        registerBackgroundMessage();
    }
}

// Request user permission for notifications
export async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
        const token = await messaging().getToken();
        return token;
    }
}

// Register background handler
const registerBackgroundMessage = () => {
    console.log("bg")
    if(Platform.OS === 'ios'){
        messaging().setBackgroundMessageHandler(async remoteMessage => {
            console.log('Notification reçue en fond ! : ', remoteMessage);
            if(remoteMessage.data && remoteMessage.data.sync_required == 1){
                syncCalendarEventId();
            }
        });
    } else if(Platform.OS === 'android'){
        const headlessNotificationHandler = async (remoteMessage) => {
            console.log('Notification reçue en fond ! : ', remoteMessage);
            // Ajoutez ici toute logique que vous souhaitez traiter en arrière-plan
        };
        
        // Enregistrez la tâche headless
        AppRegistry.registerHeadlessTask(
            'ReactNativeFirebaseMessagingHeadlessTask', 
            () => headlessNotificationHandler
        );
    }
};

The second idea I get (but the worst I think) is to try syncing the event every 30 minutes or every hour. I try to do that with the react-native-background-fetch library, but still not working. I don’t know why, but my code is not running event after 20 or 25 minutes. Here is my code for this library :

  useEffect(() => {
    const configureBackgroundFetch = async () => {
      console.log("configure bg");
      BackgroundFetch.configure(
        {
          minimumFetchInterval: 15,
          stopOnTerminate: false,
          startOnBoot: true,
        },
        async (taskId) => {
          console.log("sync")
          syncCalendarEventId();
          console.log(`Tâche de fetch avec ID ${taskId} exécutée`);
          BackgroundFetch.finish(taskId);
        },
        (error) => {
          console.error('Erreur de configuration BackgroundFetch:', error);
        }
      );
      
      console.log("fetch start");
      BackgroundFetch.start();
      console.log("fetch started");
    };

    configureBackgroundFetch();

  }, []);

For information, the useEffect is in my App.js file. And for the background fetch library, I already install it properly I think.

  • I checked background fetch, background precessing, and background notifications in xcode
  • I updated the file Info.plist with the code below :
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
        <string>fetch</string>
        <string>processing</string>
    </array>

So my question is : Is it possible to create a function like a calendar sync in background, or I just let the sync when the user opens my app ?

Thank you for your precious help 🙂