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 🙂

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật