firebase__WEBPACK_IMPORTED_MODULE_1__.default.app.ref is not a function - javascript

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

Related

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 sign in with google for web not redirecting

I was working on a react project in which I wanted to implement google sign in so I used firebase and wrote the following code:
import {initializeApp} from "firebase/app";
import "firebase/auth";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: "****",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export default app;
Creating Context to make the function accessible in the whole application:
import React from 'react';
import FirebaseContext from './FirebaseContext';
import { auth } from '../Firebase/firebase';
import { signInWithRedirect,GoogleAuthProvider,createUserWithEmailAndPassword } from "firebase/auth";
const FirebaseState = (props)=>{
const reactSignup = (email,password)=>{
return createUserWithEmailAndPassword(auth,email,password);
}
const googleSignin = ()=>{
const provider = new GoogleAuthProvider();
return signInWithRedirect(auth,provider);
}
return(
<FirebaseContext.Provider value={{reactSignup,googleSignin}}>{props.children}</FirebaseContext.Provider>
)
}
export default FirebaseState;
Calling the function on the desired button click
const {googleSignin} = useContext(FirebaseContext);
const handleGoogleSignin = async()=>{
try{
console.log("Sign in attempted");
await googleSignin();
history.push("/main");
}catch(err){
console.log(err);
}
}
Now the problem is that whenever I am running application using npm run start and the button is clicked it does not redirect for sign in but when the application is stopped then it is able to redirect but as my application is no more running that is of no use.
30 sec screen recording of the problem
Do you try to change signInWithRedirect to signInWithPopup ?
So
import React from 'react';
import FirebaseContext from './FirebaseContext';
import { auth } from '../Firebase/firebase';
import { signInWithPopup,GoogleAuthProvider,createUserWithEmailAndPassword } from "firebase/auth";
const FirebaseState = (props)=>{
const reactSignup = (email,password)=>{
return createUserWithEmailAndPassword(auth,email,password);
}
const googleSignin = ()=>{
const provider = new GoogleAuthProvider();
return signInWithPopup(auth,provider);
}
return(
<FirebaseContext.Provider value={{reactSignup,googleSignin}}>{props.children}</FirebaseContext.Provider>
)
}
export default FirebaseState;
Alternative Idea
Detact signInWithRedirect from Context and use the funct directly in your component function like this:
import { auth, provider } from '../../config';
import { signInWithPopup } from '#firebase/auth';
import { Button } from '#chakra-ui/button';
export default function Signup() {
const loginWithGoogle = () => {
signInWithPopup(auth, provider);
};
return (
<div>
<Button onClick={loginWithGoogle}>Signin With Google</Button>
</div>
);
}
Alternative Idea 2
Go to Firebase Panel > Authentication > Sign-in Method
Check your domain, if your domain is in the list delete and add again. Else add your domain.

Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.app.auth is not a function

ok so ive been building a discord clone with react redux, right now im stuck on the sign in page. it keeps giving me this error "Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_0_.app.auth is not a function" heres my code in firebase.js
import { initializeApp } from "firebase/app";
import { getDatabase } from 'firebase/database';
import { getAuth } from "firebase/auth"
import { GoogleAuthProvider } from "firebase/auth";
const firebaseConfig = {
apiKey: "AIzaSyD0RxEfG1qZ4Qsoelw5E6J0rIaJSP4BbXQ",
authDomain: "diacromb.firebaseapp.com",
projectId: "diacromb",
storageBucket: "diacromb.appspot.com",
messagingSenderId: "237625612351",
appId: "1:237625612351:web:2527b57f858d5a4688008a",
measurementId: "G-3DEREK47Q2"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth();
const provider = new GoogleAuthProvider();
export {auth , app };
export {provider};
export default db;
heres my code for Login.js
import { Button } from '#material-ui/core'
import { auth, app } from './firebase'
import { provider } from './firebase'
import { signInWithPopup } from "firebase/auth"
import React from 'react'
import './Login.css'
function Login() {
/* const signIn = () =>{
const googleAuthProvider = new GoogleAuthProvider();
app.auth().signInWithPopup(googleAuthProvider);
} */
const signIn = ()=>{
var google_provider = provider;
app.auth().signInWithPopup(provider)
.then((re)=>{
console.log(re)
})
.catch((err)=>{
console.log(err)
})
}
return (
<div className='login'>
<h2> I am the login page</h2>
<Button onClick={signIn}>Sign In</Button>
</div>
);
}
export default Login
I have no idea whats going on, ive read some other posts and people are saying to install older versions of firebase, I tried to do that and it still didnt work. Ive been stumped on this for nearly 2 days now
I assume you are using firebase 9. there you have to use js modules.
https://firebase.google.com/docs/web/modular-upgrade
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});

React Native app doesn't connect with Firebase anymore

I am facing an issue for the last 2 weeks. I was able to connect successfully my React Native app to Firebase and could see the details on the Firebase console. However, 2 weeks back the app suddenly stopped working. All I see now is a white screen. I am trying to capture Facebook Login through Firebase and tried removing firebase code and was successfully able to connect with the FB(So I guess the issue is with Firebase connection).
Any pointers will be highly appreciated.
Here is my code
App.js
import React from 'react';
import Login from './screens/Login';
import reducers from './redux/reducers';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
const middleware = applyMiddleware(thunkMiddleware)
const store = createStore(reducers, middleware);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Login/>
</Provider>
);
}
}
Login Screen
import React from 'react';
import styles from '../styles'
import NavigationContainer from '../navigation/RootNavigator';
import { connect } from 'react-redux';
import { login } from '../redux/actions'
import * as firebase from 'firebase';
import firebaseConfig from '../config/firebase.js'
import * as Facebook from 'expo-facebook';
firebase.initializeApp(firebaseConfig);
import {
Text,
View,
Alert,
TouchableOpacity
} from 'react-native';
class Login extends React.Component {
state = {}
UNSAFE_componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user != null) {
this.props.dispatch(login(true))
console.log("We are authenticated now!" + JSON.stringify(user));
}
});
}
login = async () => {
try {
await Facebook.initializeAsync({
appId: '1742056282625463',
});
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
// Build Firebase credential with the Facebook access token.
const credential = await firebase.auth.FacebookAuthProvider.credential(token);
// Sign in with credential from the Facebook user.
firebase.auth().signInWithCredential(credential).catch((error) => {
// Handle Errors here.
Alert.alert("Try Again")
});
} else {
// type === 'cancel'
Alert.alert("Cancel")
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
render() {
if(this.props.loggedIn){
return (
<NavigationContainer/>
)
} else {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.login.bind(this)}>
<Text>{this.props.loggedIn}</Text>
</TouchableOpacity>
</View>
)
}
}
}
function mapStateToProps(state) {
return {
loggedIn: state.loggedIn
};
}
export default connect(mapStateToProps)(Login);
Firebase
var firebaseConfig = {
apiKey: "AIzaSyCWjS5WxFgaBajsWKQPFLbC9QekmyxiO7I",
authDomain: "bookworm-d8e9f.firebaseapp.com",
databaseURL: "https://bookworm-d8e9f.firebaseio.com",
projectId: "bookworm-d8e9f",
storageBucket: "bookworm-d8e9f.appspot.com",
messagingSenderId: "1097080341399",
appId: "1:1097080341399:web:767ce9b106a13ae103bad2",
measurementId: "G-2JY9B79XCC"
};
// Initialize Firebase
//firebase.initializeApp(firebaseConfig);
//firebase.analytics();
module.exports = firebaseConfig
Redux - Action
export function login(input){
return function(dispatch){
dispatch({ type: 'LOGIN', payload: input });
}
}
Redux - Reducers
export default reducers = (state = {
loggedIn: false,
}, action) => {
switch (action.type) {
case 'LOGIN': {
return { ...state, loggedIn: action.payload }
}
}
return state;
}

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