How to get data from firebase cloud firestore in react - javascript

I am able to post data in firebase cloud firestore, but I am facing problem in getting data from that.
Below are my code
firebase.js
import firebase from "firebase";
var firebaseApp = firebase.initializeApp({
apiKey: "XXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXX"
})
var db = firebaseApp.firestore();
export { db };
Below code is to get data from firebase cloud firestore:
FormStatus.js:
import React, { Component } from "react";
import { db } from "../firebase";
class FormStatus extends Component {
constructor(props) {
super(props);
this.state = { form: [], }
}
componentDidMount() {
db.database().ref("form").on("value", snapshot => {
let form = [];
snapshot.forEach(snap => {
form.push(snap.val());
})
this.setState({ form: form })
});
}
render() {
return (
<div>
{this.state.form.map(data => {
return (
<ul>
<li>{data.name}</li>
<li>{data.location}</li>
</ul>
)
})}
</div>
)
}
}
export default FormStatus;
I am getting the following error:
TypeError: _firebase__WEBPACK_IMPORTED_MODULE_2__.db.database is not a function

Your code is effectively trying to execute this:
firebase.firestore().database()
That's not valid. If you want the Firebase Database reference, you should simple execute:
firebase.database()
This means you probably don't want to export firebase.firestore() from your firebase.js file. Firestore is a different database with a different API.
You could export this:
export { firebaseApp };
Then import later like this:
import { firebaseApp } from "./firebase"
firebaseApp.database().ref(...)

Change db.database().ref("form") to db.collection("form")

Related

Why does my react app go blank when I import {db} from firebase?

I am currently making an instagram clone and now am on the part where I need to use useEffect in React to Push or Pull data from Firebase Google Database. When I input:
import { db } from './firebase
my react app goes blank and I can not figure out what percisely is wrong but I know its within me trying to import db from firebase.
This is my code is firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseApp = firebase.initializeApp({
apiKey: "xxxxxx",
authDomain: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx",
measurementId: "xxxxx"
});
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export { db, auth, storage, firebase};
And this is my code in App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import Post from './Post';
import { db } from './firebase';
function App() {
const [posts, setPosts] = useState([
{
username: "Jonz",
caption: "SO COOL!",
imageUrl:"https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&w=1000&q=80"
},
{
username:"Sammiez",
caption:"That is so funny!",
imageUrl:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvojQij-7EYR5_qyxwZ5ri3NfuiUsLdQQukFcHFoOpVA&s"
}
]);
// useEffect -> Runs a piece of code based on a specific condition
useEffect(() => {
// this is where code runs
db.collection('posts').onSnapshot(snapshot => {
// every time a new post is added, this code fires
setPosts(snapshot.docs.map(doc => doc.data()))
})
}, []);
return (
<div className="App">
<div className="app__header">
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/logged_out_wordmark.png/7a252de00b20.png"
alt=""
/>
</div>
<h1> I need to learn more about react</h1>
{
posts.map(post => (
<Post username={post.username} caption={post.caption} imageUrl={post.imageUrl}/>
))
}
{/* Post */}
{/* Post */}
</div>
);
}
export default App;
I have not tried anything. I believe it is because I don't have the right syntax for firebase v9 , but I don't know the correct way to go about it. Any help would be appreciated.
You could try the imports this way according to documentation :
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from 'firebase/storage'
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx",
measurementId: "xxxxx"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth();
const storage = getStorage();
export { db, auth, storage};
Example for getStorage() from documentation : https://firebase.google.com/docs/storage/web/create-reference . Check all the create reference tabs for each you're wanting to use

Uncaught TypeError: database.ref is not a function using vue 3

I've spent a good few hours searching around here but nothing wanted to work. I want to use firebase realtime database but whatever I try, I just keep getting errors. The aim of this webapp is to add, edit, view and delete products from a list. This is what I have in the data.js so far. Any help would be appreciated :)
import firebase from 'firebase/compat/app';
import store from "./store";
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/database';
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
databaseURL: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const database = getFirestore();
export default function setListingData() {
database.ref("/listings")
.get()
.then(function(snapshot) {
if (snapshot.exists()) {
let listings = [];
snapshot.forEach((e) => {
listings.push(e.val());
});
console.log(listings);
store.commit("initListings", listings);
return snapshot.val();
} else {
console.log("No data available");
}
})
.catch(function(error) {
console.error(error);
});
}
export function deleteListing(id) {
firebase
.database()
.ref(`/listings/${id}`)
.remove();
}
/**
* Add/edit listing
* #param {*} listing The listing
*/
export function addListing(listing) {
console.log("ADDING:", listing);
firebase
.database()
.ref(`/listings/${listings.id}`)
.set(listings);
}
export function emptyListing() {
return {
title: "",
price: "",
description: ""
};
}
You're mixing up Firestore and the Realtime Database here. While both databases are part of Firebase, they are completely separate and each has its own API.
As shown in the documentation on getting started with the Realtime Database and in the section on using the compat libraries, you get a database instance with:
import firebase from 'firebase/compat/app';
import store from "./store";
import 'firebase/compat/auth';
import 'firebase/compat/database'; // 👈
// 👆 Remove all Firestore imports, and all fine-grained improts
And then
firebase.initializeApp(firebaseConfig);
// Get a reference to the database service
var database = firebase.database();

how can i to refencer a realtime database at my reactjs aplication

i'm trying to refencer a realtime database at my reactjs aplication but it's not working.I created a file for firebase config named firebase.js and i import that one in ./home/index.js Visual Studio code does not report the error, but when i look the DevTool report a errors.
1.Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.default.app.ref is not a function
firebase.js
import {initializeApp}from 'firebase/app';
import { getAuth} from 'firebase/auth';
import { getDatabase} from 'firebase/database';
const firebaseAPP =initializeApp( {
apiKey: "AIzaSyCtYdRuFmkC3Mx7dcRLBcY-HYPitRuMD2Y",
authDomain: "reactproject-2d567.firebaseapp.com",
databaseURL:"https://reactproject-2d567-default-rtdb.firebaseio.com/",
projectId: "reactproject-2d567",
storageBucket: "reactproject-2d567.appspot.com",
messagingSenderId: "199332161332",
appId: "1:199332161332:web:828be709a4d0109df62761",
measurementId: "G-F517JH6WEJ"
});
const auth = getAuth(firebaseAPP)
const db = getDatabase(firebaseAPP)
class Firebase{
constructor(){
this.app = getDatabase(firebaseAPP);
}
//metodo de login
login(email,password){
return auth.signInWithEmailAndPassword(email,password)
}
async register(nome,email,password){
await auth.createUserWithEmailAndPassword(email,password)
const uid= auth.currentUser.uid
return db.ref('usuario').child(uid).set({nome:nome})
}
isInitialized(){
return new Promise(resolve =>{
auth.onAuthStateChanged(resolve)
})
}
}
export default new Firebase();
index.js
import React, { Component } from 'react';
import firebase from '../../firebase';
import './home.css'
class Home extends Component {
state ={
posts:[]
}
componentDidMount(){
firebase.app.ref('posts').once('value', (snapshot)=>{
let state = this.state;
state.posts =[]
snapshot.forEach((childItem)=>{
state.posts.push({
key:childItem.key,
titulo:childItem.val().titulo,
image:childItem.val().image,
descricao:childItem.val().descricao,
autor:childItem.val().autor,
})
})
this.setState({state})
})
}
render(){
return(
<div> home</div>
)
}
}
export default Home

firebase__WEBPACK_IMPORTED_MODULE_1__.default.app.ref is not a function

i'm trying to refencer a realtime database at my reactjs aplication but it's not working.I created a file for firebase config named firebase.js and i import that one in ./home/index.js
Visual Studio code does not report the error, but when i look the DevTool report 3 errors.
1.Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.default.app.ref is not a function
2.The above error occurred in the component
3.Uncaught (in promise) TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.default.app.ref is not a function
1.firebase.js
import {initializeApp}from 'firebase/app';
import { getAuth} from 'firebase/auth';
import { getDatabase} from 'firebase/database';
const firebaseAPP =initializeApp( {
apiKey: "AIzaSyCtYdRuFmkC3Mx7dcRLBcY-HYPitRuMD2Y",
authDomain: "reactproject-2d567.firebaseapp.com",
databaseURL:"https://reactproject-2d567-default-rtdb.firebaseio.com/",
projectId: "reactproject-2d567",
storageBucket: "reactproject-2d567.appspot.com",
messagingSenderId: "199332161332",
appId: "1:199332161332:web:828be709a4d0109df62761",
measurementId: "G-F517JH6WEJ"
});
const auth = getAuth(firebaseAPP)
const db = getDatabase(firebaseAPP)
class Firebase{
constructor(){
this.app = getDatabase(firebaseAPP);
}
//metodo de login
login(email,password){
return auth.signInWithEmailAndPassword(email,password)
}
async register(nome,email,password){
await auth.createUserWithEmailAndPassword(email,password)
const uid= auth.currentUser.uid
return db.ref('usuario').child(uid).set({nome:nome})
}
isInitialized(){
return new Promise(resolve =>{
auth.onAuthStateChanged(resolve)
})
}
}
export default new Firebase();
2../home/index.js
import React, { Component } from 'react';
import firebase from '../../firebase';
import './home.css'
class Home extends Component {
state ={
posts:[]
}
componentDidMount(){
firebase.app.ref('posts').once('value', (snapshot)=>{
let state = this.state;
state.posts =[]
snapshot.forEach((childItem)=>{
state.posts.push({
key:childItem.key,
titulo:childItem.val().titulo,
image:childItem.val().image,
descricao:childItem.val().descricao,
autor:childItem.val().autor,
})
})
this.setState({state})
})
}
render(){
return(
<div> home</div>
)
}
}
export default Home

Firebase onAuthStateChanged error with React

I'm trying to check if a user is logged in or not on my React webpage using Firebase, however I keep getting an error TypeError: Cannot read property 'onAuthStateChanged' of undefined, the line of code it links to is as followed:
Login.js:
authListener() {
Fire.auth.onAuthStateChanged((user) => {
if (user) {
this.setState({ user })
} else {
this.setState({ user: null })
}
})}
Fire.js:
import firebase from 'firebase'
const config = {
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx"
};
const Fire = firebase.initializeApp(config);
export default Fire;
** solved it, above is what my Fire.js and Login.js look like for those coming and having the same problem **
You need to include firebase package
import firebase from "firebase";
and then use auth() function of firebase
authListener() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ user })
} else {
this.setState({ user: null })
}
})}
if you are importing firebase from another file then configure it like this
import firebase from 'firebase/app';
import 'firebase/auth';
export const init = () => {
let config = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: 'xxxxxxxxxxxxx'
};
firebase.initializeApp(config);
};
export const firebaseAuth = firebase.auth;

Categories

Resources