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;
Related
I'm very new and trying to set Firebase Google authentication in Expo RN app,
Expo docs code snippet below:
https://docs.expo.dev/guides/authentication/#google
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import { ResponseType } from 'expo-auth-session';
import * as Google from 'expo-auth-session/providers/google';
import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider, signInWithCredential } from 'firebase/auth';
import { Button } from 'react-native';
// Initialize Firebase
initializeApp({
/* Config */
});
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [request, response, promptAsync] = Google.useIdTokenAuthRequest(
{
clientId: 'Your-Web-Client-ID.apps.googleusercontent.com',
},
);
React.useEffect(() => {
if (response?.type === 'success') {
const { id_token } = response.params;
const auth = getAuth();
const provider = new GoogleAuthProvider();
const credential = provider.credential(id_token);
signInWithCredential(auth, credential);
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();
}}
/>
);
}
I'm getting error something like that:
TypeError: provider.credential is not a function. (In 'provider.credential(_id_token)', 'provider.credential' is undefined)
Any solution?
Thanks in advance
Replace the following code:
const provider = new GoogleAuthProvider();
const credential = provider.credential(id_token);
with:
const credential = GoogleAuthProvider.credential(idToken);
I believe the expo docs need to be updated to reflect this.
Recently I started to use Pinia as a global store for my Vue 3 Project. I use Firebase for the user authentication and am trying to load the current user before Vue is initialized. Ideally everything auth related should be in a single file with a Pinia Store. Unfortunately (unlike Vuex) the Pinia instance needs to be passed to the Vue instance before I can use any action and I believe that is the problem. On first load the user object in the store is empty for a short moment.
This is the store action that is binding the user (using the new Firebase Web v9 Beta) in auth.js
import { defineStore } from "pinia";
import { firebaseApp } from "#/services/firebase";
import {
getAuth,
onAuthStateChanged,
getIdTokenResult,
} from "firebase/auth";
const auth = getAuth(firebaseApp);
export const useAuth = defineStore({
id: "auth",
state() {
return {
user: {},
token: {},
};
},
actions: {
bindUser() {
return new Promise((resolve, reject) => {
onAuthStateChanged(
auth,
async (user) => {
this.user = user;
if (user) this.token = await getIdTokenResult(user);
resolve();
},
reject()
);
});
},
// ...
}})
and this is my main.js file
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { createPinia } from "pinia";
import { useAuth } from "#/store/auth";
(async () => {
const app = createApp(App).use(router).use(createPinia());
const auth = useAuth();
auth.bindUser();
app.mount("#app");
})();
How can I set the user before anything else happens?
I figured it out. Had to register the router after the async stuff
//main.js
(async () => {
const app = createApp(App);
app.use(createPinia());
const { bindUser } = useAuth();
await bindUser();
app.use(router);
app.mount("#app");
})();
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()
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();
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';