Firebase onAuthStateChanged error with React - javascript

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;

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

React Firebase Error: import declarations may only appear at top level of a module

I install firebase in my react project using npm install firebaseand I initialize the firebase config then when I run my app It went blank.
Uncaught SyntaxError: import declarations may only appear at top level of a module bundle.js:121943:1 in my console
My config file init-firebase.js
import { initializeApp } from "firebase/app";
import {getFirestore} from 'firebase/firestore';
const firebaseConfig = {
apiKey: "AIzaSyClp0O4aHwqL6o7cDx3urbDXPpJWazxnWI",
authDomain: "city-truck.firebaseapp.com",
projectId: "city-truck",
storageBucket: "city-truck.appspot.com",
messagingSenderId: "1052243135965",
appId: "1:1052243135965:web:654cc786da98502037fa34",
measurementId: "G-S4HLEKZ9RS"
};
// Import the functions you need from the SDKs you need
const app = initializeApp(firebaseConfig);
// Initialize Firebase
export const db = getFirestore(app);
import { collection,getDocs } from 'firebase/firestore';
import { db } from '../lib/init-firebase';
const getData = () => {
const taskData = collection(db,'Tasks')
getDocs(taskData)
.then(response => {
console.log(response)
})
.catch(error => console.log(error.message))
}
useEffect(() => {
getData()
},[])

#firebase/firestore: Firestore (9.9.3): INTERNAL UNHANDLED ERROR: TypeError: protoLoader.fromJSON is not a function

Currently getting this error when trying to initialise firestore on my Nextjs website. This is localhost instance. This does work on another computer and on my deployed version so I'm not too sure what's going on here. I have already done an npm install. And all the config is already set correctly.
My firebase initialisation code for reference:
import { FirebaseOptions, getApp, initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: `${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseapp.com`,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: `${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.appspot.com`,
messagingSenderId: `${process.env.NEXT_PUBLIC_FIREBASE_SENDER_ID}`,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
const createFirebaseApp = (config: FirebaseOptions) => {
try {
return getApp();
} catch {
return initializeApp(config);
}
}
const app = createFirebaseApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export {auth, db};

How can I show my Images from Firebase Storage to my website?

<template>
<div>
<input type="file" id="dosya" #change="putDesign()" />
</div>
</template>
<script>
import { initializeApp } from "firebase/app";
import { getStorage, ref, uploadBytes, listAll } from "firebase/storage";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export default {
data() {
return {
fileName: "",
resim: "",
photos: [],
};
},
methods: {
mounted() {
// Create a reference under which you want to list
const listRef = ref(storage, "design/");
// Find all the prefixes and items.
listAll(listRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
console.log(folderRef);
});
res.items.forEach((itemRef) => {
// All the items under listRef.
this.photos.push(itemRef+ " ");
});
})
.catch((error) => {
// Uh-oh, an error occurred!
console.log(error);
});
},
};
</script>
I can add files to my Firebase Storage, but I cannot show them on my website. I can get Local Storage Location but I cannot get Access Token, so I cannot open or show photos. Is there a way to get the Access Token? I searched on Firebase Documentation, but couldn't find anything helpful.
You just need to get the downloadURL for each element in the folder. It could look like this:
import { initializeApp } from "firebase/app";
import { getStorage, ref, uploadBytes, listAll, getDownloadURL } from "firebase/storage";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export default {
data() {
return {
fileName: "",
resim: "",
photos: [],
};
},
methods: {
mounted() {
// Create a reference under which you want to list
const listRef = ref(storage, "design/");
// Find all the prefixes and items.
listAll(listRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
console.log(folderRef);
});
res.items.forEach((itemRef) => {
// All the items under listRef.
getDownloadURL(itemRef).then(downloadURL=>{
this.photos.push(downloadURL);
})
});
})
.catch((error) => {
// Uh-oh, an error occurred!
console.log(error);
});
},
};

How to get data from firebase cloud firestore in react

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")

Categories

Resources