I've started migrating over to v9 Modular firebase. Please see my config:
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
..
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = getDatabase(app);
Then in another file I made basic CRUD functions.
import { database } from "./firebase"
export const insertTestData = () => {
return database.ref("test").set({name:"hello world"})
}
I got the following error:
Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.database.ref is not a function
Did I miss anything?
I'm not sure why it's also not picking up imports
You are importing ref() from Modular SDK but still using name-spaced syntax.
Try:
import { getDatabase, ref, set } from "firebase/database";
export const insertTestData = () => {
return set(ref(database, "test"), { name: "hello" })
}
Make sure you are referring to the "Modular" tab of the code snippets in the documentation
Related
here's my code, it is the exact copy of the docs but it says that ref.on is not a function. maybe i forgot to put a module in the import but i couldn't find any information about that.
function readpixels() {
const db = getDatabase();
const ref = ref(db, 'pixels');
ref.on('value', (pixel) => {
console.log("read")
})
}
and here are the import lines:
import { initializeApp } from "firebase/app";
import { getDatabase, ref, push, set } from "firebase/database";
You're importing the new v9 functions, but in your code you are then trying to use the older syntax. You'll have to pick one or the other.
In v9 syntax, the ref.on("value" would be:
import { onValue } from "firebase/database";
...
onValue(ref, (pixel) => {
console.log("read")
}
Also see the Firebase documentation on reading from the Realtime Database with the v9 SDK.
hello first time posting so i have been struggling with this error and tried fix of others here and it didnt work here is my firebase_init.js code:
import * as firebase from "firebase/app";
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export { db, auth };
And after checking documentation i copied these codes to index.html in the public folder of the react project:
<script defer src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
// ...
<script defer src="../src/firebase-init.js"></script>
still nothing worked, tried different imports, i also tried deleting node modules and package-lock.json and reinstalling, it just ended up messing up a whole lot of stuff in the node modules, so that didn't work either. So any help to solving this will be appreciated.
Update your firebase file to include the imports for the services you are planning to use. The script references may simply not be available at the time you are attempting to initialize auth and firestore:
import firebase from "firebase/app";
// static import of firestore
import "firebase/firestore";
// static import of auth
import "firebase/auth";
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export { db, auth };
Keep in mind, this is for version 8 of firebase. The newer version at the time of this answer, version 9, will look pretty different:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore/lite';
import { getAuth } from 'firebase/auth';
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth(db);
export { db, auth };
So I have a simple React Native app that I created using Expo and debug on my personal Android device.
I've included firebase/firestore into my app and am now trying to add an object to firestore on button click.
Here's my code:
firebaseConfig.js :
import { initializeApp } from '#firebase/app';
var config = {
...
}
const app = initializeApp(config);
export default app;
Component:
import { app } from '../firebaseConfig';
import { getFirestore } from 'firebase/firestore/lite';
import { doc, setDoc, collection, query, where, getDocs, initializeFirestore } from "firebase/firestore";
...
export default function Component() {
const firestoreDb = getFirestore(app);
// this function is called when clicking a button
const onAddListPress = () => {
setDoc(doc(firestoreDb, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
}
}
This throws the following error:
Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
This code above (in the onPress) is copied from the official firestore docs, here:
https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document
Does anyone have an idea why this does not work?
I suggest you edit your post and remove the firebaseConfig configuration keys, or delete your Firebase app and create a new one from the Firebase console to secure your app. I tried to replicate your application using React, and I received the same error message. There were two changes I made to correct the error. The first one is inside the firebaseConfig file, the default export needs to be changed to a named export:
import { initializeApp } from "firebase/app"
const firebaseConfig = {
//Project configuration keys
};
const app = initializeApp(firebaseConfig);
export { app }; // Change from a default to a named export
In addition, all the imports inside your component should come from the full Javascript SDK, not the lite version. The lite version has some limitations which can result in this specific error.
import { app } from "./firestore-config";
import { getFirestore, getDoc, doc } from "firebase/firestore";
import './App.css';
export default function App() {
const firestoreDB = getFirestore(app);
const docRef = doc(firestoreDB, "users", "testUser1");
const getData = async () => {
const data = await getDoc(docRef);
console.log(data);
}
getData();
return <div className="App"></div>;
}
You might also want to review this GitHub issue if you are using yarn to manage your dependencies.
Other important information:
Project uses React Library
Initialized with Create React App
This is how my code typically looks like on v8:
// firebase.js
import firebase from "firebase/app";
import "firebase/firestore";
export const app = firebase.initializeApp(config);
export const firestore = app.firestore();
// app.js
import { firestore } from './firebase'
firestore.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
});
I believe with v9, Firebase no longer has that side effect import problem, and so now we explicitly state what functions we want from a package.
// firebase.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
export const app = initializeApp(config)
export const firestore = getFirestore()
Code below is from Firebase docs
// app.js
import { addDoc, collection } from "firebase/firestore";
try {
const docRef = await addDoc(collection(db, "users"), {
first: "Alan",
middle: "Mathison",
last: "Turing",
born: 1912
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
Will the code above (which uses the addDoc and collection imports) refer to the initialized Firestore instance in firebase.js, or is there a proper way to use the initialized Firestore instance?
Firestore instances are managed from the core Firebase App, the firestore modules only include the libraries to make the requests. The solution to getting the Firestore instance without having to reference the core app is to request the instance from the Firestore modules.
import { getFirestore } from 'firebase/firestore';
const db = getFirestore();
Source: https://firebase.google.com/docs/firestore/quickstart#initialize
I am trying to import firebase app (8.0.2) on the client side without bundler.
I downladed the firebase-app.js from the CDN and host it on my server.
The goal is to have the firebase app module imported in one of my modules like this:
import firebase from '/vendor/firebase-app.js';
However, when trying to access firebase, I am getting an error about the default export not being defined. In firefox, this is:
Uncaught SyntaxError: import not found: default
Where am I wrong? Does the module import only work with a bundler?
I believe I have some fundamental misunderstanding, but I cant figure it out.
Thanks for the help!
As Doug comments, that syntax is intended for use with bundlers.
If you want to import the SDK inside a module script then you will need to use a CDN, like this:
useEffect(() => {
let isSubscribed = true
const initFirebase = async () => {
try {
const [{
initializeApp
},
{
getFirestore,
collection,
addDoc
}
] = await Promise
.all([
import('https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js'),
import('https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js')
])
const fireApp = initializeApp(firebaseConfig)
const appDB = getFirestore(fireApp)
if (isSubscribed) {
setFirebase(fireApp)
setDB(appDB)
setResult('success')
}
} catch (e) {
console.log(e);
setResult('error')
}
}
if (firebaseConfig) {
initFirebase()
.catch(e => {
console.log(e);
})
}
return () => is Subscribed = false
}, [firebaseConfig])
That's from a POC I'm working on, single HTML file, Preact + Firebase, no bundlers needed.
It is still a long way to be something and need validations, but it answers your question.
Here is the repo.
In Firebase "^9.9.4" use :
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {}
export const app = initializeApp(firebaseConfig);
export const db = getFirestore(app)