Error message - Uncaught Reference Error: firebase is not defined - database

Someone should assist me.
I'm getting this error message.
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"; const firebaseConfig = { }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app);

Related

Firestore object is sometimes undefined and sometimes works fine

I am using NextJS and Firebase fairly new to both. My app is trying to collect data from firestore database on some occasions it works fine and sometimes it returns "n is undefined" refering to the firestore object "db". This happens when i call the "collection(db, "users", uid, "posts")" function in the [posts].js file. What is causing this?
Firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import {getStorage} from "firebase/storage"
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const storage = getStorage(app);
export const db = getFirestore(app);
[posts].js
import { useRouter } from 'next/router'
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useAuth } from '../context/AuthContext'
import styles from '../styles/dashboard.module.css';
import Image from 'next/image';
import { collection, getDocs } from "firebase/firestore";
import { db } from '../lib/firebase';
export default function Posts(){
const [queriedData, setQueriedData] = useState([]);
const router = useRouter()
const { uid } = router.query
useEffect(() => {
async function fetchData() {
const postsRef = collection(db, "users", uid, "posts");
const snapshot = await getDocs(postsRef);
const postData = snapshot.docs.map((doc) => {
const data = doc.data();
data.id = doc.id;
return data;
});
setQueriedData(postData);
}
fetchData();
}, []);
return(
{queriedData.map((post) =>(<div>post.title</div>)
)}
}
Added await to the collection function and I also thought it was internet issues hence i setup a firebase emulator still got the same behavior.
I tried console logging "db" right after the line "export const db = getFirestore(app);". I got out "[Object Object]"

React Testing Error: Jest encountered an unexpected token

I am conducting test using the React Testing Library with Jest. I have a test file as such:
import React from "react";
import { render as rtlRender, fireEvent } from "#testing-library/react";
import Component from "./..";
import { data, userId } from "./testConstants";
import { Provider } from "react-redux";
import store from "redux/store";
const render = (component) =>
rtlRender(<Provider store={store}>{component}</Provider>);
describe(InvoiceList, () => {
it("Number of invoice list item is rendered correctly according to search input", () => {
const { getByTestId } = render(<Component userId={userId} data={data} />);
fireEvent.change(getByTestId("search-input"), {
target: { value: "bacardi" },
});
fireEvent.click(getByTestId("all-tab"));
expect(queryAllByTestId("invoice-list-item")).toHaveLength(3);
});
});
I ran the test, but got an error where Jest encountered an unexpected token. This error has details stating SyntaxError: await is only valid in async function and shows me that the error occur from an import in import { auth } from "services/firebase".
services/firebase.ts
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore, initializeFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
export const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
const config = {
development: {
...
},
production: {
...
},
};
const firebaseConfig = isLocalhost
? config.development
: await fetch("/__/firebase/init.json").then((response) => response.json()); // THE ERROR DETAILS SHOW THAT THE ERROR IS FROM THIS LINE OF CODE
// eslint-disable-next-line max-len
// This will use our config to recognize the project and initialize authentication and database modules.
export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
initializeFirestore(app, {
ignoreUndefinedProperties: true,
});
export const db = getFirestore(app);
export const storage = getStorage(app);
I'm not sure what is wrong right here, the firebase auth can be used correctly during development and production but I'm getting the error during testing.

Getting error when firebase SignOut on react native

All works ok, sign in, signup, even the database, but when I am trying to sign out this error show up:
[TypeError: undefined is not an object (evaluating
'_$$_REQUIRE(_dependencyMap[0],
"#firebase/util").getModularInstance(auth).signOut')]
This is my firebase file:
import { initializeApp, getApps} from 'firebase/app';
import {initializeAuth, getAuth} from 'firebase/auth';
import { initializeFirestore } from 'firebase/firestore';
import { getReactNativePersistence } from 'firebase/auth/react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import {REACT_APP_APIKEY,
REACT_APP_AUTHDOMAIN,
REACT_APP_PROJECTID,
REACT_APP_STORAGEBUCKET,
REACT_APP_MESSAGINGSENDERID,
REACT_APP_APPID
} from "#env"
// Firebase config
const firebaseConfig = {
apiKey: REACT_APP_APIKEY,
authDomain: REACT_APP_AUTHDOMAIN,
projectId: REACT_APP_PROJECTID,
storageBucket: REACT_APP_STORAGEBUCKET,
messagingSenderId: REACT_APP_MESSAGINGSENDERID,
appId: REACT_APP_APPID,
};
// initialize firebase
let firebaseApp;
let auth;
if (getApps().length < 1) {
firebaseApp = initializeApp(firebaseConfig);
auth = initializeAuth(firebaseApp, {
persistence: getReactNativePersistence(AsyncStorage),
});
} else {
auth = getAuth();
}
export default auth;
export const database = initializeFirestore(firebaseApp, {
experimentalForceLongPolling: true,
});
This is when I am calling the function:
import { signOut } from 'firebase/auth';
import {database, auth} from '../config/firebase';
const onSignOut = () => {
try {
signOut(auth).then(()=> console.log("signout"))
} catch (error) {
console.log('Error logging out: ', error)
}
};
I finally found the problem, it was my mistake.
As you can see in my firebase file, I export the "auth" as default, but when I am trying to import it, I am importing inside the curly braces {auth}, but It must be outside due it is default. I fixed that and the problem is fixed.
this is the right way:
import auth, {database} from '../config/firebase';

FirebaseError: Expected type 'Ia', but it was: a custom Oa object

Not sure why I am getting this error, here's my setup. this error only happens for firestore. Auth, functions, storage, realtimedb work not sure what I'm missing. I followed The firebase documentation to set up.
firebase.js
import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
import { getDatabase, connectDatabaseEmulator } from "firebase/database";
import {
getAuth,
connectAuthEmulator,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from "firebase/auth";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import {
getFunctions,
connectFunctionsEmulator,
httpsCallable,
} from "firebase/functions";
import { getStorage, connectStorageEmulator } from "firebase/storage";
import Constants from "expo-constants";
// Initialize Firebase
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
dataBaseURL: Constants.manifest.extra.databaseURL,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId,
};
const app = initializeApp(firebaseConfig);
export const firestore = {
instance: () => {
return getFirestore(app);
},
connectFirestoreEmulator: (host, port) => {
return connectFirestoreEmulator(getFirestore(app), host, port);
},
};
if (__DEV__) {
try {
firestore.connectFirestoreEmulator("localhost", "8080");
console.log("====================================");
console.log("connected to emulators....");
console.log("====================================");
} catch (error) {
console.log("====================================");
console.log(error, "error connectiong emulators");
console.log("====================================");
}
}
Since you mentioned that the error seems to happen only in Firestore, I have followed the documentation related to using the Firestore emulator, and my app successfully connects to the local emulator and retrieves local data.
I’m not sure if the way you export the Firestore instance is causing the issue, but the documentation shows that the function must be imported and used, passing the Firestore instance as an argument. This is the sample code I tested:
firestore-config.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// Configuration keys
};
const app = initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
app.js
import { firestore } from "./firestore-config";
import { getDoc, doc, connectFirestoreEmulator } from "firebase/firestore";
import "./App.css";
export default function App() {
try{
connectFirestoreEmulator(firestore, "localhost", "8080");
console.log("connected");
const docRef = doc(firestore, "localTest", "localTestDoc");
const getData = async () => {
const docSnap = await getDoc(docRef);
console.log(docSnap.data());
}
getData();
}
catch(err){
console.log("error: ", err)
}
return <div className="App"></div>;
}
I am able to see my data coming from the emulated Firestore as output. It would also be useful to see a full error stack trace, since the error from the title is not really that descriptive.

Firebase error: No firebase app default has been created

I am making a food delivery app using react-native and redux. I want to fetch the data from the firebase store and for that, I have written a function in the actions.js, but whenever I run the app it shows the Error
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
Here is the function which I am using to fetch the data
action.js
import firebase from "firebase"
export const ProductDetails = (data) => {
return {
type: "PRODUCT_ITEMS",
payload: {
data,
},
};
};
var db = firebase.firestore();
var docRef = db.collection("Products").doc("Items");
export const FetchItems = () => {
return async function (dispatch) {
return await docRef
.get()
.then((doc) => {
if (doc.exists) {
console.log("Document Data", doc.data());
dispatch(ProductDetails(doc.data));
} else {
console.log("NO such document");
}
})
.catch((error) => {
console.log(error);
});
};
};
Here is my App.js file
import React, { useState } from "react";
import { StyleSheet, Text, View, Dimensions } from "react-native";
import { NavigationContainer } from "#react-navigation/native";
import AppStack from "./components/navigation/AppStack";
import firebase from "firebase";
import {Provider} from "redux"
import store from "./store"
import { useDispatch, useSelector, Provider } from "react-redux";
import store from "./redux/store";
import AppWrapper from "./AppWrapper";
export default function App() {
const firebaseConfig = {
};
if (firebase.apps.length === 0) {
firebase.initializeApp(firebaseConfig);
}
return (
<Provider store={store}>
<NavigationContainer>
<AppStack />
</NavigationContainer>
</Provider>
);;
}
I would recommend creating a separate file firebase.js and export Firebase services from there after initialization.
firebase.js
import firebase from 'firebase/app';
import 'firebase/firestore'
const firebaseConfig = {...};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
export const auth = firebase.auth();
export const firestore = firebase.firestore()
Then import these wherever you need them:
// App.js for example
import {firestore, auth} from './firebase.js'
//var docRef = firestore.collection("Products").doc("Items");
for users with expo(v44) and firebase(v9)
firebaseUtil.js
import { initializeApp, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
// Initialize Firebase
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
export { db, auth };
Login.js
import { auth } from "../../util/firebaseUtil";
export default function Login() {
const onSignUp = () => {
signInWithEmailAndPassword(auth, email, password);
};
return (
...
)
}
I think my error is caused by Webpack chunking(bootstrap). I did import the file with initializeApp(). My work around for who has the same problem.
Modularize the initializeApp in one file(initFire for me) and export anything(doesn't have to be app)
Import & Export before first usage of getApp()(methods like getAuth() will call it),
In this way, after Webpack it will still run first. (ES6 export {app} from "./initFire")
(This answer is grepped from my own GitHub Wiki, not plagiarizing)

Resources