Cannot import Firebase Firestore Colletion - javascript

I'm trying to call a Firestore Colletion in my next app, here is the error that I get when running the app:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
Here is my firebase.js code:
import firebase from 'firebase/app';
import "firebase/firestore"
const firebaseConfig = {};
export const getPosts = async () => {
firebase.initializeApp(firebaseConfig);
const posts = await firebase.firestore().collection("articles").then((snapshot) => {
const snapshotVal = snapshot.val();
const result = [];
for (var slug in snapshotVal) {
const post = snapshotVal[slug];
result.push(post);
}
return result.reverse();
});
return posts
};

Because you keep trying to initialize a new firebase app every time you getPosts, so you should check first if there isn't a firebase app before initializeApp,
try something like this before getPosts function:
var firebase_app;
if (!firebase.apps.length) {
firebase_app = firebase.initializeApp(firebaseConfig);
} else {
firebase_app = firebase.app(); // if already initialized, use that one
}

Related

Firebase Realtime data is only available after saving the edited source file?

I'm relatively new to RN / Javascript, so this might be a rookie mistake - strangely I couldn't find anything close to it on my research.
My setup: I'm developing a RN app with Expo and I'm using the Expo Go app to see any changes.
Since I want to enable cloud services, I'm using the Firebase Realtime database with the official packages in my app. So far, so good.
My issue: Every time I start the developement server (npm start) or reload the app with the 'r' shortcut on my Accounts screen (basic screen displaying the names of the accounts the user created), see attached screenshot, the app refuses to load the data from Realtime - instead I'm greeted with a 'undefined is not an object (evaluating 'obj['accounts']'). Once I hit 'STRG + S' on my keyboard in any file opened, the Expo Go app refreshes and the data is somehow found.
If anyone could help me with this issue, you would surely save my day. :)
CODE
My data is loaded from here (dataHandler.js):
// auth stuff
import { Auth, getAuth } from "firebase/auth";
// database stuff
import { db } from "./firebase";
import { get, onValue, ref } from 'firebase/database'
// more auth stuff
const auth = getAuth()
const userID = auth.currentUser?.uid;
// database Path for retrieving data
const databasePath = userID
export var cachedData = {};
// Gets data from the firebase server, set's it to a local value
export function getData() {
return onValue(ref(db, databasePath), querySnapshot => {
let data = querySnapshot.val() || {};
let downloadedData = {...data};
// set data to a public var
cachedData = downloadedData;
console.log('DEBUG: Data loaded from the server')
})
}
My account data is then loaded from here (accountData.js):
// load the data from dataHandler.js
import { cachedData } from "./dataHandler";
import { getAuth } from "firebase/auth";
const auth = getAuth()
const userID = auth.currentUser?.uid;
export function getAccountData() {
console.log('accountData receives = ', cachedData)
let obj = cachedData[userID];
let accounts = obj['accounts'];
console.log('getAccountData returns: ', accounts)
return accounts;
}
I'm calling the files here:
// experimental stuff
import { getData } from '../../core/dataHandler';
import { getAccountData } from '../../core/accountData'
const Accounts = () => {
// Downloads data on the app start
getData();
// load the data for the account
const accounts = getAccountData()
console.log('accountData = ', accounts)
const accountKeys = Object.keys(accounts)
const [ accountName, setAccountName ] = useState('')
return( <SomeView /> )
}

How to use setDoc with Firebase-Admin with Typescript in firestore?

I have config/firebase.ts:
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'
const firebaseAdminApp = initializeApp({
credential: cert({
privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}),
databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});
const firestore = getFirestore(firebaseAdminApp);
export default firestore
and when trying to upsert, I have:
import firestore from "../config/firebaseAdmin";
const upsertInstance = async (instance: Instance) => {
const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
return res
}
but I get:
Error: expected a function
What am I doing wrong?
Firebase Admin is not totally modular yet like the client SDK yet so you would have to use namespaced syntax. Admin SDK's Firestore instance won't work perfectly with client SDK functions. Try refactoring the code as shown below:
export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"
const upsertInstance = async (instance: Instance) => {
const res = await db.doc(`instances/${instance.uri}`).set(instance);
return res;
}
Checkout the documentation for more information.

firebase realtime database undefined function

I'm trying to retrieve from a realtime db I started by init the app with the configuration like so
import {initializeApp} from 'firebase/app';
import {getDatabase} from 'firebase/database';
let config = {
apiKey: 'xxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxx',
...
};
const app = initializeApp(config);
const database = getDatabase(app);
then when I try using the database variable it crashes
componentDidMount() {
database
.ref(`master/tickets`)
.once('value', snapshot => {
var obj = snapshot.val();
console.log('obj :', obj);
})
.catch(error => {
console.log(error);
});
}
I also have tried firebase.database.ref() it shows error cannot find variable firebase
What I am doing wrong? It was working fine in previous builds
The Firebase Web SDK underwent major breaking changes with the update to V9.0.0.
Please see the upgrade guide for details on how to modify older patterns to the new API.
import { ref, get } from "firebase/database";
import { database } from "...";
/* ... */
componentDidMount() {
get(ref(database, 'master/tickets'))
.then(snapshot => {
const obj = snapshot.val();
console.log('obj :', obj);
})
.catch(error => {
console.log(error);
});
}

Uncaught Error: Service database is not available firebase javascript

I am trying to access my realtime database in firebase but it shows me this error Uncaught Error: Service database is not available. I have searched for what this could posabbly mean but I couldn't find anything useful or a solution.
Here is my code:
window.addPerson = addPerson;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userVar = urlParams.get('user')
const userVarSplitted = userVar.split('#')
const userVarFormatted = userVarSplitted[0] + ":" + userVarSplitted[1]
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-analytics.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {MY FIREBASE CONFIG};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
if (app.length === 0) {
console.log("no firebas app")
}else{
console.log("initialized")
}
const analytics = getAnalytics(app);
const database = getDatabase(app);
function addPerson() {
set(ref(database, "verified/" + userVarFormatted), {
name: userVarSplitted[0],
discriminator: userVarSplitted[1]
});
console.log("added")
PS: The script type is set to modular.
Do you know what the error means and what is happening?
You're using difference versions of the Firebase SDKs. I'd update the database import to version 9.6.4 too, so that the all Firebase SDK versions are the same.

"firebaseApp.auth.RecaptchaVerifier is not a constructor" error when using firebase phone authentication in Reactjs

I am importing 'firebaseApp' from a file where I have done all the setup of firebase and I have implemented email, google and Facebook authentication but when I am implementing the phone number auth the ReCaptcha is not a constructor I am using ReactJs functional component.
Is there any way of implementing phone number auth without ReCaptcha or if not how can I fix the error.
Setup of firebase
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore';
// Web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
export const firebaseApp = firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const db = firebase.firestore();
export const google_provider = new firebase.auth.GoogleAuthProvider();
export const facebook_provider = new firebase.auth.FacebookAuthProvider();
This is the place I am taking the number as user input and sending the OTP for verification but the sample code number is hardcoded.
import { firebaseApp, auth } from '../../../firebase/firebasesetup'
function Form() {
const setuprecaptcha = () => {
window.recaptchaVerifier = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container',
{
'size': 'invisible',
'callback': function (response) {
console.log("captcha resolved");
// sendsms();
}
});
}
const sendsms = () => {
setuprecaptcha();
var phoneNumber = '+918220310506';
var appVerifier = window.recaptchaVerifier;
auth.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
window.confirmationResult = confirmationResult;
}).catch(function (error) {
alert("not sent")
});
}
return (
<input type="text" placeholder="Mobile" value={mob}
onChange={e => setMob(e.target.value)} />
<div id="recaptcha-container"></div>
<button onClick={sendsms} id='sign-in-button'>Send otp</button>
)
}
export default Form
Ok, so I am answering My own question. This kind of looks Weird but still if anyone of you faces the same problem as mine.
2 things I need to solve in the firebase_setup file and add the main function in React functional component. (Total 3 updates)
firebase_setup file
first
import firebase from 'firebase'; and not import firebase from 'firebase/app';
second
firebase.initializeApp(firebaseConfig); export const firebaseApp = firebase
React functional component
import { firebaseApp} from './firebase_setup';
const sendsms = () => {
//If you want to make the recaptcha invisible
var recaptcha = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible'
});
//If you want to make the recaptcha visible
var recaptcha = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container');
//Your phone number with the country code
var number = '+**********';
//actual code begins here
auth.signInWithPhoneNumber(number, recaptcha).then(function (e) {
var code = prompt("enter the code sent to your mobile number");
if (code === null) return;
e.confirm(code).then(function (result) {
alert(result.user + ' verified ')
}).catch(function (error) {
alert('Could not verify,Please try again');
});
}).catch(function (error) {
alert('Please try again.We were unable to reach your phone.Select the correct code and the phone number');
});
}

Categories

Resources