firebase__WEBPACK_IMPORTED_MODULE_2___default error firebase and react - javascript

I have this firebase error I am receiving, never seen It before. I had used stripe api / extension in connection with firebase and when i'm go to save the data in firebase db, it gives me the error firebase__WEBPACK_IMPORTED_MODULE_2___default function
Here is my code "db.js" :
import getStripe from "./stripe";
import firestore from "../firebase/index"
export async function createCheckoutSession (uid){
const checkout_sessionsRef =await firestore
.collection('user')
.doc(uid)
.collection('checkout_sessions')
.add({
price : 'price_1IGEdTKDPaWWeL1ymwWH5Ubb',
success_url :window.location.origin,
cancel_url:window.location.origin,
});
checkout_sessionsRef.onSnapshot(async (snap) => {
const {sessionId} =snap.data();
if (sessionId ){
const stripe = await getStripe();
stripe.redirectToCheckout({sessionId})
}
})
}
any ideas on how to fix?

Related

"query is not a function" Next Js getServerSideprops and firebase error

I'm using NextJS and firebase as my primary database for the app that I'm currently building for an NGO. and I ran into an issue.
import {
collection,
where,
query,
getDocs
} from '#firebase/firestore';
import { db } from '../../../services/firebase';
export async function getServerSideProps({query}) {
const user = await getDocs(query(collection(db, 'members'), where('id', '==', query)))
return {
props: {
// VisionInfo: JSON.stringify(user.docs.map(item => item.data()))
json: JSON.stringify('Hello')
}
};
}
The only way to get Query from the URL in NextJS in serverSideProps is to use the keyword "query" but the same keyword is used to fetch firebase document.
The error shows "query is not a function"
Is there anyway I could get Query into serversideprops ?
The issue arises because you also have "query" in getServerSideProps parameters. Try naming the import from Firestore SDK (or the query param) as shown below:
import { query as fireQuery } from '#firebase/firestore';
export async function getServerSideProps({query}) {
const user = await getDocs(fireQuery(collection(db, 'members'), where('id', '==', query)))
// use fireQuery here ^^^
})

Can't make Firestore to get only docs from logged user id

I am an UX Designer and I'm pretty new to working with Firebase.
I've been trying to develop a system on webflow integrated with Firebase using JavaScript and the Firebase SDK to a personal project and got stuck with this problem.
I have managed to create the authentication system, the signup system and everything is working as it should.
However, when I try to fetch data from Firestore userdata collection, I am not being able to get the current user id and pass it to the WHERE string on my query.
If I run the query without the WHERE, it works perfectly, bringing me all the documents in the userdata collection, but when I try to do it only for a specific user, it fails.
I already tried a lot of things which I think wasn't the right method to do this, the JavaScript below was my last attempt. I think I'm just too new on this and can't understand how to pass the id variable into the query.
Here is the link to the project: https://poupei.webflow.io/. Just click "Criar conta" to create an account, you can use a fake email and 6 digit password and then login.
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getAuth, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
import { getFirestore, collection, getDocs, query, where, doc } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js"
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const app = initializeApp({
apiKey: "AIzaSyAZUIyxf4Lsw6D9JOzVuNslsGJ8gXkPBVY",
authDomain: "poupei-app.firebaseapp.com",
projectId: "poupei-app",
storageBucket: "poupei-app.appspot.com",
messagingSenderId: "837432279066",
appId: "1:837432279066:web:119bc86e42fb87ac17d1a3"
});
// Initialize Firebase
const auth = getAuth()
const db = getFirestore();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const userID = user.id;
console.log("Logged In");
console.log(userID);
// ...
} else {
// User is signed out
window.location.replace("https://poupei.webflow.io/");
}
});
const q = query(collection(db, "userdata"), where("id", "==", userID));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
const docs = doc.data();
document.getElementById('nome').innerHTML = docs.nome;
document.getElementById('sobrenome').innerHTML = docs.sobrenome;
document.getElementById('email').innerHTML = docs.email;
document.getElementById('saldo').innerHTML = docs.saldo;
});
document.getElementById('logoutBtn').addEventListener('click', function(){
signOut(auth).then(() => {
// Sign-out successful.
window.location.replace("https://poupei.webflow.io/");
}).catch((error) => {
// An error happened.
});
});
</script>
´´´
#Allennick has the cause of the problem correct in their answer, but the solution won't work.
Signing in to Firebase (as well as loading data from Firestore and most other modern cloud APIs) is an asynchronous operation. While the user is being signed in (or the data is being loaded) your main code continues to run. Then when the user is signed in, your callback code is executed.
It's easiest to see this flow by running in a debugger, or adding some logging:
console.log("Attaching auth state listener");
onAuthStateChanged(auth, (user) => {
if (user) {
console.log("Got user state");
}
});
console.log("Starting database query");
const q = query(collection(db, "userdata"), where("id", "==", userID));
const querySnapshot = await getDocs(q);
When you run this code it logs:
Attaching auth state listener
Starting database query
Got user state
This is probably not the order you expected, but it perfectly explains why you're not getting the user data from the database: the query executes before the user is ever loaded.
The solution to this problem is always the same: any code that needs to react to the current user state, needs to be inside the onAuthStateChanged callback, be called from there, or otherwise synchronized.
The simplest fix is to move your database code into the callback, like this:
onAuthStateChanged(auth, async (user) => {
if (user) {
const userID = user.id;
// 👇 Now that the user us know, we can load their data
const q = query(collection(db, "userdata"), where("id", "==", userID));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
const docs = doc.data();
document.getElementById('nome').innerHTML = docs.nome;
document.getElementById('sobrenome').innerHTML = docs.sobrenome;
document.getElementById('email').innerHTML = docs.email;
document.getElementById('saldo').innerHTML = docs.saldo;
});
document.getElementById('logoutBtn').addEventListener('click', function(){
signOut(auth).then(() => {
// Sign-out successful.
window.location.replace("https://poupei.webflow.io/");
}).catch((error) => {
// An error happened.
});
} else {
// User is signed out
window.location.replace("https://poupei.webflow.io/");
}
});
Also see:
firebase.auth().currentUser is null at page load
Is there any way to get Firebase Auth User UID?
firebase.initializeApp callback/promise?
I think that the query doesn't know what userID is because you are declaring that variable inside authStateChange. Try to move the declaration of userID to global scope + add a console.log() before executing the query to see if the userID is set correctly.
Or just put the code that performs the query inside the onAuthStateChanged code so that you can use the userID.
(Posted answer on behalf of the question author to move it to the answer space).
Updating with the code that worked for me with the help of Frank. Thanks Frank!
onAuthStateChanged(auth, async (user) => {
if (user) {
const userID = user.email;
console.log(userID);
const q = query(collection(db, "userdata"), where("email", "==", userID));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
const docs = doc.data();
document.getElementById('nome').innerHTML = docs.nome;
document.getElementById('sobrenome').innerHTML = docs.sobrenome;
document.getElementById('email').innerHTML = docs.email;
document.getElementById('saldo').innerHTML = docs.saldo;
document.getElementById('meta').innerHTML = docs.objetivo;
})
} else {
console.log("nada");
}
});

What's wrong with my code? My React Native App crashes on calling firestore without any log

Here's my implementation, I'm storing the baseURL on my firestore database. I used to sign in anonymously in order to get the url. But on calling the firestore, my app crashes without any error, warning, etc.
import {create} from 'apisauce';
import auth from '#react-native-firebase/auth';
import firestore, {firebase} from '#react-native-firebase/firestore';
const apiClient = create({
method: 'POST',
});
apiClient.addAsyncRequestTransform(async request => {
await auth()
.signInAnonymously()
.then(() => {
console.log('success');
})
.catch(error => {
console.log(error);
});
const url = await firestore()
.collection('service_url')
.doc('service_url')
.get()
.then(document => console.log(document.data))
.catch(error => console.log(error));
console.log(url);
request.baseURL = url;
auth().signOut();
});
export default apiClient;
The problem I faced was the okHTTP. It was not working with Android API 30. So, after so much workaround, I added the okhttp dependency to my project. That solved my error.

An error occured: Cannot read property 'stripeId' of null

i changed my stripe and firebase api keys and everything back to test mode for some testing purposes. However, I was unpleasantly presented with this error in my console when trying to redirect to checkout using the firebase stripe api:
An error occured: Cannot read property 'stripeId' of null
however, no where in my code does stripeID exist. interesting. here's the code. oh and keep in mind this only happens in test mode.
var userID = "";
firebase.auth().onAuthStateChanged((user) => {
if(user) {
userID = user.uid
console.log(user.uid)
}
});
export async function createCheckoutSession(activtyStatus){
var price = 'price_1Iav0JKDPaWWeL1yBa9F7Aht'
if (activtyStatus == "canceled") {
// test price
price = 'price_1IelOCKDPaWWeL1ynps36jkc'
}
const checkoutSessionRef = firestore
.collection('customers')
.doc(userID)
.collection('checkout_sessions')
.add({
price: price,
success_url: "https://app.x.com/successPage",
cancel_url: "https://app.x.com/signin",
});
// Wait for the CheckoutSession to get attached by the extension
(await checkoutSessionRef).onSnapshot(function (snap) {
const { error, sessionId } = snap.data();
if (error) {
// Show an error to your customer and
// inspect your Cloud Function logs in the Firebase console.
console.log(`An error occured: ${error.message}`);
}
if (sessionId) {
// We have a session, let's redirect to Checkout
// Init Stripe
const stripe = window.Stripe('pk_test_C');
console.log("going to stripe: ")
stripe.redirectToCheckout({sessionId})
console.log("logged stripe")
}
});
}
export async function goToBilliingPortal(){
var finalRoute = "https://app.x.com/profile"
const functionRef = app
.functions('us-central1')
.httpsCallable('ext-firestore-stripe-subscriptions-createPortalLink');
const {data} = await functionRef({returnUrl : finalRoute});
window.location.assign(data.url);
};
does anyone have any ideas?
Have you checked what the logs of your Stripe dashboard or Firebase Functions say?
I faced similar issue, and looking at the logs it was because of a failure of the createCheckoutSession function. I was having the following message in my Firebase logs:
ext-firestore-stripe-subscriptions-createCheckoutSession
❗️[Error]: Failed to create customer for [XXXXXXXXXXXXXXXXXXXXXX]: This API
call cannot be made with a publishable API key. Please use a secret
API key. You can find a list of your API keys at
https://dashboard.stripe.com/account/apikeys.
I simply had to replace the key in "Stripe API key with restricted access" in Firebase console with a restricted key and it was solved.
I had the same issue, for me it was that my card was declined by google clouds since my card eas expired. I updated my account with another card and no more issues.

firebase__WEBPACK_IMPORTED_MODULE_2___default error react.js

I have this firebase error I am receiving, never seen It before. I had used stripe api / extension in connection with firebase and when i'm go to save the data in firebase db, it gives me the error firebase__WEBPACK_IMPORTED_MODULE_2___default function
Here is my code "db.js" :
import getStripe from "./stripe";
import firestore from "../firebase/index"
export async function createCheckoutSession (uid){
const checkout_sessionsRef =await firestore
.collection('user')
.doc(uid)
.collection('checkout_sessions')
.add({
price : 'price_1IGEdTKDPaWWeL1ymwWH5Ubb',
success_url :window.location.origin,
cancel_url:window.location.origin,
});
checkout_sessionsRef.onSnapshot(async (snap) => {
const {sessionId} =snap.data();
if (sessionId ){
const stripe = await getStripe();
stripe.redirectToCheckout({sessionId})
}
})
}
any ideas on how to fix?

Categories

Resources