Firebase: react-native: get instance id, iid from '#react-native-firebase/iid' not working - firebase

My code to used to work. It did:
import iid from '#react-native-firebase/iid';
...
tokenDevice = await iid().getToken();
But now, I get
TypeError: (0, _iid.default) is not a function. (In '(0, _iid.default)()', '(0, _iid.default)' is undefined)
It seems my code cannot import '#react-native-firebase/iid' anymore.
Besides, other firebase packages have versions 12+, package iid is stuck at 11.5, and react-native firebase documentation does not reference iid anymore
https://rnfb-docs.netlify.app/reference
What can I do to get my device token to send messages to a particular phone ?

The iid module was deprecated. The right code to get the token is
import messaging from '#react-native-firebase/messaging'
const deviceToken = await messaging().getToken()

Related

Firebase Firestore error XMLHttpRequest is not defined developing google chrome extension MV3

I am developing a google chrome extension with manifest version 3 using Firebase and Firestore for store user data.
When I try to write on the Firestore i'll get this error: Uncaught ReferenceError: XMLHttpRequest is not defined
My firebase-main.js looks like this:
import "/firebase-app.js";
import "/firebase-auth.js";
import "/firebase-firestore.js";
try {
const firebaseConfig = {
apiKey: "MYDATAHERE"
authDomain: "MYDATAHERE",
projectId: "MYDATAHERE",
storageBucket: "MYDATAHERE",
messagingSenderId: "MYDATAHERE",
appId: "MYDATAHERE"
};
console.log("firebase main inizializing");
const app = firebase.initializeApp(firebaseConfig);
console.log(app);
const db = firebase.firestore();
console.log(db);
chrome.runtime.onMessage.addListener((msg, sender, resp) => {
console.log("msg.command = " + msg.command);
if(msg.command == "post"){
console.log("msg = post");
console.log("msg.data.extensionEmail is " + msg.data.extensionEmail);
db.collection("users").doc(msg.data.extensionEmail).set({
data: msg.data
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
sendResponse(true);
return true;
})
} catch (e) {
console.error(e);
}
Inside my extension popup.js i'll send the message to firebase-main and the message is received but when it try to write on Firebase the error comes out.
I am using firebase-app, firebase-firestore and firebase-auth 8.5 downloaded inside the main directory of the extension.
I read that XMLHttpRequest is no more supported with service worker in manifest version 3 but I can't find a way to write on the db.
Can anyone help me please?
I've already tryed to import xhr2 using the command npm install xhr2 and import at the top of firebase-firestore.js without success.
I've tryed using newer/older versions of firebase-app, firebase-firestore and firebase-auth.
ServiceWorkers in Chrome Extensions using Manifest V3 can no longer access XMLHTTPRequest and instead use fetch(). This means that you may have to find a polyfill for it, however, this does come with some inherint challenges once you do find a polyfill. One challenge is that XHR synchronous operations cannot be replicated in fetch completely since fetch is an asynchronous API by design. Additionally, you would need to place some trust in the authors of the polyfill that they are not doing anything nefarious with their polyfill library that you are using. If I was you, I would determine what functionality you are looking to use in Firestore and either call a cloud function from an HTTPS endpoint with the firebase functions you want or, if you are interested in querying firestore, utilizing the REST API and the fetch API to make those commands.

Inconsistency with Authenitcaiton User-Creation in Firebase React Native

I am trying to incorporate the Firebase JS SDK into a managed Expo React Native project. I installed Firebase through npm i firebase and I am using the latest version.
The problem is that whenever I start the expo app, through an Android emulator, I, when passing the input from formik into createUserWithEmailAndPassword first get the auth/network-request-failed error message, but after clicking the signup button several times, more than 10, it somehow works. The user is then added to the Firebase console. After this it works flawlessly, and I can create multiple accounts without fail. However, should I restart the app, then I would have to repeat the steps above.
I have divided the main firebase function to a separate file, and imported it.
The exported file:
import { initializeApp } from 'firebase/app';
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth';
import firebaseConfig from './app/config/Firebase/firebaseConfig';
let myApp = initializeApp(firebaseConfig);
const auth = getAuth(myApp);
export function signupEmail(email, password) {
console.log(email, password);
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
console.log('Signed in');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
The main parts of the sign-up file:
function handleSignup(values) {
signupEmail(values.email, values.password);
}
<SubmitButton
style={styles.signupButton}
title='SignUp'
onPress={handleSubmit}
/>
onSubmit={(values) => [handleSignup(values)]}
After pressing Signup I get the email and password printed out, as in the signupEmail function. I get the email and password message whether or not it is successful in the end, which I assume implies the problem doesn't lie with formik, since the data is correctly passed to the signupEmail function. Though, from here it often stands idle, sometimes for more than 10s before the network error message comes up. When it is successful, I think, is always instant.
I also have a print-out auth.currentUser button, which returns null whilst the process is loading, and if successful logs out the expected object. Though, sometimes it logs out the object to an account whose email that I didn't add during the current session. I did also add a Sign Out function which turns the auth.currentUser object into null.
I don't know where to go from here, and would appreciate any help!
This issue seems to be related to the Android emulator, Expo Go on my phone worked without issue.

Why Do I Keep Getting This CORS Error With Firebase

I keep getting this same CORS error when trying to perform basic requests with the Firebase real-time database.
Ive followed 2 separate tutorials on how to request/post data to/from the Firebase real-time database and every time I reload the page it comes up saying:
Access to script at 'https://console.firebase.google.com/project/ProjectName*******/database/data/' (redirected from 'https://***ProjectName*****-default-rtdb.firebaseio.com/') from origin 'http://localhost:5005' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have googled this and have tried many solutions, some from this site and nothing has helped.
Ive installed GSUTIL and tried to modify the CORS rules through that...
Eg. Running gsutil cors set cors.json gs://your-bucket Through GSUTIL
It just returns 'No file in directory'
I then tried putting a cors.json file in my firestore and it still doesn't help
Im just at a loss and have no idea what to do now
I am just getting started with coding and know nothing about CORS
So please take note of that...
Any help would be greatly appreciated
When importing getDatabase to use the Firebase RTDB, you don't want to use either of these:
import { getDatabase, ... } from "https://[PROJECT_ID]-default-rtdb.firebaseio.com/"
const { getDatabase, ... } = await import("https://[PROJECT_ID]-default-rtdb.firebaseio.com/")
This is because neither of these are importing the Firebase Web SDK.
To import the Firebase Web SDK for the RTDB in a build environment, you would use either of these:
import { getDatabase, ... } from "firebase/database"
const { getDatabase, ... } = await import("firebase/database");
To import the Firebase Web SDK for the RTDB in a browser, you would use either of these:
import { getDatabase, ... } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js"
const { getDatabase, ... } = await import("https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js");
The URL of your database normally goes into the Firebase configuration object you pass to initializeApp like so:
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com", // <-- here
storageBucket: "bucket.appspot.com"
};
const app = initializeApp(firebaseConfig);
Then when you need to use it, you just call either of these as needed:
// uses default app & default database
const database = getDatabase();
// uses given app & default database
const database = getDatabase(app);
When you are using more than one RTDB instance (shared from another project, different region, etc), you pass in the URL of that instance as the second argument like so:
// uses default app & given database
const secondDatabase = getDatabase(getApp(), "https://secondDatabaseName.firebaseio.com");
// uses given app & given database
const secondDatabase = getDatabase(app, "https://secondDatabaseName.firebaseio.com");

Stripe error using Firebase Functions: Error: You did not provide an API key. You need to provide your API key in the Authorization header

I have written a Firebase Function that is called when a new user is created using the Firebase Authentication. It then tries to create a Stripe Customer but I get the following error in the Firebase Log:
createStripeCustomer
Error: You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/. at IncomingMessage.<anonymous> (/workspace/node_modules/stripe/lib/StripeResource.js:174:21) at Object.onceWrapper (events.js:420:28) at IncomingMessage.emit (events.js:326:22) at IncomingMessage.EventEmitter.emit (domain.js:506:15) at endReadableNT (_stream_readable.js:1241:12) at processTicksAndRejections (internal/process/task_queues.js:84:21)
The complete function is shown below and has been deployed to Firebase. The Stripe secret key is loaded from a config file:
import * as functions from "firebase-functions";
import {stripe} from "../../config";
export const createStripeCustomer = functions.auth.user().onCreate(async (user) => {
const customer = await stripe.customers.create({
email: "paying.user#example.com",
source: "src_18eYalAHEMiOZZp1l9ZTjSU0",
});
console.log("customer_Id# ", customer.id);
});
Can anyone explain why I am getting the error and how I can fix the problem?
Many thanks.
I fixed my own problem. The secret key was incorrectly labelled so it wasn't being loaded properly.

AngularFire httpsCallable Object(...) is not a function

I want to call a httpsCallable function in my Ionic 3 app. I am attempting to follow these docs: https://firebase.google.com/docs/functions/callable
I tried:
const newGame = (firebase as any).functions().httpsCallable('findCreateGame');
newGame({}).then(function(result) {
console.log("In here.");
});
Which resulted in:
ERROR TypeError: WEBPACK_IMPORTED_MODULE_5_firebase_functions.functions is not a function
I also tried the newly implemented wrapper in angularfire:
const newGame = this.afFunctions.httpsCallable('findCreateGame');
newGame({}).then(function(result) {
console.log("In here.");
});
ERROR TypeError: Object(...) is not a function
Does anyone have any experience with this yet? Here is the pull request to add the functionality if that helps at all. https://github.com/angular/angularfire2/pull/1532
EDIT---
This code actually calls the Cloud function even though it throws the same 'Not a function' error:
const newGame = this.afFunctions.httpsCallable('findCreateGame');
newGame();
I'm not sure how else to call the function, even though newGame is an object and not a function reference.
The Object(...) is not a function is thrown because you're running rxjs 5, rather than 6.
If you upgrade, the function will perform as expected.
See the rxjs migration doc for more details on the changes between 5 and 6.
In your first example make sure you are importing import 'firebase/functions' in the ts file you're calling the function.

Resources