"_auth.default.auth" is not a function react-native - firebase

i have installed latest version of react-native and firebase. when im trying to call "firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password)" its getting an error and its saying "_auth.default.auth is not a function"
in root folder files not getting this kind of error. its working. but im getting inside folder file and call fire base function this error will occur.
Root folder file App.js
"firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password)"
Working..
./src/component/LoginForm.js
"firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password)"
not working. getting above error.
------------------App.js Root level (working code with "firebase.auth().onAuthStateChanged((user)" )-------------------
import React, { Component } from 'react';
import { View } from 'react-native';
import { Header, Button, Spinner } from './components/common';
import LoginForm from './components/LoginForm';
import firebase from '#firebase/app';
class App extends Component {
state = { loggedIn: false };
componentWillMount() {
var config = {
apiKey: 'xxxxxxxxxxxxxxx-MY',
authDomain: 'xxxx-a115e.firebaseapp.com',
databaseURL: 'https://xxxx-xxxx.firebaseio.com',
projectId: 'xxx-xx',
storageBucket: 'xxxx-a115e.appspot.com',
messagingSenderId: 'xxxxxxxxx'
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged((user) => {
if(user) {
this.setState({ loggedIn: true });
}else {
this.setState({ loggedIn: false });
}
});
}
-------------/src/components/LoginForm.js file not working (firebase.auth().signInAndRetrieveDataWithEmailAndPassword)---------------
import React, { Component } from 'react';
import { firebase } from '#firebase/auth';
import { Text } from 'react-native';
import { Button, Card, CardSection, Input, Spinner } from './common';
class LoginForm extends Component {
state = { email: '', password: '', error: '', loading: false };
onButtonPress() {
const { email, password } = this.state;
//var user = firebase.auth().currentUser;
this.setState({ error: '', loading: true});
firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password)
.then(this.onLoginSucess.bind(this))
.catch( () => {
firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(email, password)
.then(this.onLoginSucess.bind(this))
.catch(this.onLoginFail.bind(this));
});
}
i identified this happening because of file is not in root level of project files structure. help me to get solution for this..

New firebase API have to use import like this for Auth.
import firebase from 'firebase/app';
import 'firebase/auth';
I am using firebase version 5.11.0. hope this helps :)

Spent a day on this, and this is the only thing I could get to work for me.
Worked through about 8 different tutorials, and not a single one worked. Finally combined some things from a couple of tutorials and StackOverflow and it started working:
import { getAuth } from "firebase/auth";
const auth = getAuth();

Related

Issue while implementing firebaseUi auth in a nextjs project ? [error : window is not defined]

I'm trying to setup firebase Auth into my nextjs project (it looks like the firebase documentation is not up-to-date via the release of the getAuth method).
While using firebaseUi (to get the automatic styling of the different auth providers), I get this error :
Here is the code (i'm just trying to render the firebaseUi component for now) :
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore
const db = getFirestore(app);
// Initialize Firebase Authentication
const auth = getAuth(app);
export { db, auth }
Then in a template page for signin :
import { NavBar } from '../components';
import { StyledFirebaseAuth } from 'react-firebaseui/StyledFirebaseAuth';
import { auth } from '../firebase/initFirebase';
import { GoogleAuthProvider } from 'firebase/auth';
const firebaseui = require('firebaseui')
// // Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.GoogleAuthProvider(auth);
function Signup() {
const firebaseUiConfig = {
signInFlow: 'popup',
signInSuccessUrl: '/',
tosUrl: '/terms-of-service',
privacyPolicyUrl: '/privacy-policy',
signInOptions: [
GoogleAuthProvider.PROVIDER_ID
]
}
return (
<div>
<NavBar />
<StyledFirebaseAuth uiConfig={firebaseUiConfig} firebaseAuth={auth} />
</div>
)
}
export default Signup
Thanks a lot in advance for your help, I don't understand what's going on :(
// EDIT //
I understand it has to deal with SSR. So I did try to dynamically import firebaseUi with next/dynamic. I don't get the error any longer but the page is now blank (just the navbar component renders). Is it because I am passing props inappropriately ?
import dynamic from "next/dynamic";
import { NavBar } from '../components';
import { auth } from '../firebase/initFirebase';
import { GoogleAuthProvider } from 'firebase/auth';
const AuthComponent = dynamic(() =>
import('react-firebaseui/StyledFirebaseAuth').then((mod) => mod.StyledFirebaseAuth)
)
function Signup() {
const firebaseUiConfig = {
// signInFlow: 'popup',
signInSuccessUrl: '/',
tosUrl: '/legal',
privacyPolicyUrl: '/legal',
signInOptions: [
GoogleAuthProvider.PROVIDER_ID
]
}
return (
<div>
<NavBar />
<AuthComponent uiConfig={firebaseUiConfig} firebaseAuth={auth} />
</div>
)
}
export default Signup
The idea here to disable SSR on the page which used firebaseui.
This can be done in two steps.
Use firebase ui or any library which needs window keywork to work.
import React from 'react';
import Modal from '#leafygreen-ui/modal';
import * as firebaseui from 'firebaseui'
import 'firebaseui/dist/firebaseui.css'
export default function AuthUi({open, setOpen}) {
return (
<>
<Modal open={open} setOpen={setOpen}>
// Modal Content goes here.
// Signup widgets comes here
</Modal>
</>
);
}
while importing the library, do something like this.
//__app.js
// import AuthUi from '../components/authUi'; >> Replace this by code below
import dynamic from 'next/dynamic'
const AuthUi = dynamic(
() => import('../components/authUi'),
{ ssr: false }
);
Now you would be able to use firebaseui without window error.

Firebase analytics are not supported in this enviroment [duplicate]

I have a react/nextjs app and I have firebase.js as follow:
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/analytics'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: '...'
}
try {
firebase.initializeApp(firebaseConfig)
firebase.analytics()
} catch (err) {
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
export default firebase
I kept getting
Firebase initialization error ReferenceError: navigator is not defined
after adding analytics to the firebase.js file. What is the correct way to add analytics to the app?
import { getAnalytics, isSupported } from "firebase/analytics";
const analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
Try this one
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/firestore"
import "firebase/storage"
import "firebase/analytics"
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
// Auth export
export const auth = firebase.auth()
// Firestore exports
export const firestore = firebase.firestore()
export const serverTimestamp = firebase.firestore.FieldValue.serverTimestamp
export const fbTimestamp = firebase.firestore.Timestamp
export const fromMillis = firebase.firestore.Timestamp.fromMillis
export const increment = firebase.firestore.FieldValue.increment
// Storage exports
export const storage = firebase.storage()
export const analytics = () => {
if (typeof window !== "undefined") {
return firebase.analytics()
} else {
return null
}
}
export default firebase
ReferenceError: navigator is not defined
because there is no window object present during the server-side rendering of the Nextjs application.
Try:
if(typeof window != undefined){
firebase.analytics()
}
I just updated my firebase to version 9 and this error is not seen.
Update to version 9 could be a solution to this.
But for version 9, there are some changes in firebase declaration.
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
Using firebase V 9.16 this how I solved the issue
import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";
import { getFirestore } from "firebase/firestore"
const firebaseConfig = {
...
};
let app; let analytics; let db
if(typeof window != undefined){
app = initializeApp(firebaseConfig);
analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
db = getFirestore(app)
}
export {app, analytics, db}
In _app.js I import analytics and i use useEffect like
useEffect(() => {
analytics;
}, [])

firebase.auth.GoogleAuthProvider is not a constructor

I'm trying to use google sign using firebase in the Vue framework. I don't know what the error is this can anyone help me with this.
vue.runtime.esm.js?2b0e:1888 TypeError: _firebase_js__WEBPACK_IMPORTED_MODULE_2__.fb.auth.GoogleAuthProvider is not a constructor
at VueComponent.socialLogin (Signin.vue?3d55:76)
at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1854)
at HTMLButtonElement.invoker (vue.runtime.esm.js?2b0e:2179)
at HTMLButtonElement.original._wrapper (vue.runtime.esm.js?2b0e:6917)
this is my code
firebase.js
import firebase from "firebase";
var firebaseConfig = {
config
};
const fb=firebase.initializeApp(firebaseConfig);
export { fb };
Sign in.vue
<script>
import { fb } from "../firebase.js";
export default {
name: "Signin",
components: {},
data() {
return {
};
},
methods: {
socialLogin() {
const provider = new fb.auth.GoogleAuthProvider();
fb.auth().signInWithPopup(provider).then((result) => {
this.$router.replace('home');
}).catch((err) => {
alert('Oops. ' + err.message)
});
}
}
};
</script>
The auth property (not the auth() function) is available on the static firebase object, not your firebase app.
You want something more like this
import firebase from "firebase/app"
import "firebase/auth" // 👈 this could also be in your `firebase.js` file
const provider = new firebase.auth.GoogleAuthProvider()

firebase and gatsby build don't work well together

I get the following error when I try to login:
u.a.auth is not a function
The error is on this line in Login.js:
app.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
At the top, I have import app from "./base.js";
In base.js, I have
import firebase from 'firebase/app';
var config = {
....
};
var app;
if(firebase.apps && firebase.apps.length > 0) {
app = firebase.apps[0];
} else {
app = firebase.initializeApp(config);
}
export default app;
That's after I run
gatsby build
gatsby serve
Hello here's how I did it. It worked fine:
import React from "react";
import firebase from "firebase";
...
const LoginForm = () => {
const login = values => {
firebase
.auth()
.signInWithEmailAndPassword(values.email, values.password)
.then(() => { firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
navigate("/app/profile");
})
.catch(error => {
console.log("do something with the error:", error);
});
}
return(
<form onSubmit={login}>
form details
</form>
);
};
export default LoginForm;

this.$firebase is undefined

I'm building my first Vue.js app, trying to use vuex with vuexfire.
//main.js
import firebase from 'firebase';
...
Vue.prototype.$firebase = firebase.initializeApp(config);
...
firebase.auth().onAuthStateChanged(() => {
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
render: h => h(App),
created() {
this.$store.dispatch('setDealsRef');
},
});
});
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
next('/signin');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
And:
//store/index.js
import Vue from 'vue';
import Vue from 'vue';
import Vuex from 'vuex';
import { firebaseMutations } from 'vuexfire';
...
Vue.use(Vuex);
const db = this.$firebase.firestore();
const dealsRef = db.collection('deals');
And:
//store/mutations.js
export default {
SET_USER(state) {
state.user = this.$firebase.auth().currentUser;
},
...
}
This complies OK, but throws TypeError: this.$firebase is undefined[Learn More] in the console.
Any idea what I'm doing wrong? I think I've read every relevant tutorial and StackOverflow questions, and tried everything.
When you do:
Vue.prototype.$firebase = firebase.initializeApp(config);
You add $firebase to the Vue instance. So for
this.$firebase
to work, the this should be a Vue insteance. In other words, that line must execute inside a Vue method/hook/computed/etc.
And the code you show, doesn't do that:
const db = this.$firebase.firestore();
in the code above, the this is the outer context. (Probably is window.)
So for it to work outside a Vue instance, you have to do:
const db = Vue.prototype.$firebase.firestore();
Provided the line above executes after (in time/order) the line where you initialize the $firebase.
I think I solved the problem:
Moving firebase initialization to store.js
Changing firebase.auth().onAuthStateChanged(() => { to Vue.prototype.firebase.auth().onAuthStateChanged(() => { in main.js
Importing firebase as: import firebase from '#firebase/app';
import '#firebase/firestore';

Resources