-
Hey, I've been following the guide but I'm stuck at creating a token. I'm getting this error:
I've installed the following package.json:
The errors say call initializeApp first. But I'm definitly calling initializeApp() first.. Perhaps not in the right way or place? The guide is for angular, so I'm trying to make it work for React. Below is a simplified setup without any components. Just calling initialize and then trying to get a token.
The logs show that firebase is initialised with an app Any idea why this happens? or how to get past this error? help is much appreciated as I've been stuck on this for a while now. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Try to import |
Beta Was this translation helpful? Give feedback.
-
@robingenz Thanks, i've tried that now, but unfortunately the error remains the same. I'm using dynamic imports now to ensure import {lazy, useEffect, useState} from 'react';
import {Button} from '../components/ui/forms/Button';
import {Capacitor} from '@capacitor/core';
import {initializeApp} from '@firebase/app';
const initializeFirebase = () => {
if (Capacitor.isNativePlatform()) {
return;
}
return initializeApp({
apiKey: '[removed]',
authDomain: '[removed]',
projectId: '[removed]',
storageBucket: '[removed]',
messagingSenderId: '[removed]',
appId: '[removed]',
measurementId: '[removed]',
});
};
//initialize firebase right at the start before the component renders
let app = initializeFirebase();
let reqPermission, token;
const Home = () => {
useEffect(() => {
// Dynamically import the module AFTER initializeApp, when the component has already rendered
import('@capacitor-firebase/messaging').then((module) => {
reqPermission = module.FirebaseMessaging.requestPermissions();
token = getTokenFirebase(module.FirebaseMessaging);
});
}, []);
const getTokenFirebase = async (messaging) => {
const options: any = {
vapidKey: '[removed]',
};
if (Capacitor.getPlatform() === 'web') {
options.serviceWorkerRegistration = await navigator.serviceWorker.register('firebase-messaging-sw.js');
console.log('web', options.serviceWorkerRegistration);
}
const {token} = await messaging.getToken(options);
return token;
};
return (
<div>Firebase Capacitor Test</div>
);
};
|
Beta Was this translation helpful? Give feedback.
It's working for us now. When we made a codesandbox test setup with react-create-app it was working.
In our own setup we discovered
firebase/app
was being imported as CJS whilst the dynamic import of@capacitor-firebase/messaging
would importfirebase/app
as ESM. Basically two different firebase versions were being loaded.For now we fixed that by switching our app to ESM. Once the same firebase version was loaded in both instances it worked as expected. I'll close this discussion