Firebase Auth Google Login Issue [duplicate] - javascript

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

Related

Window is not defined while using firebase auth in next.js

Following code is from firebaseConfig.js:
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
//credentials//
};
export const app = initializeApp(firebaseConfig);
export const analytics=getAnalytics(app)
export const authentication=getAuth(app);
Following code is from index.js:
export default function Home() {
const auth = getAuth();
const generateRecaptcha=()=>{
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {}, authentication);
}
window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {}, auth);
const getOTP=()=>{
generateRecaptcha()
}
I am getting error:
ReferenceError: window is not defined
After removing export getAnyalytics, I am still getting the same error but at window.recaptchaVerifier function in index.js.
Also please tell me the use of getAnalytics.
getAnalytics() will instantiate an instance of Firebase Analytics that you can use to log events throughout your app.
The solution for me when using analytics was to create a provider as follows:
FirebaseTrackingProvider.tsx
export const FirebaseTrackingProvider = (props: {children: ReactNode}) => {
const router = useRouter();
const [analytics, setAnalytics] = useState(null);
useEffect(() => {
setAnalytics(getAnalytics(firebaseApp));
if (analytics) {
setAnalyticsCollectionEnabled(analytics, true);
}
const handleRouteChange = (url: string) => {
if (!analytics) {
return;
}
logEvent(analytics, 'page_view', {
page_location: url,
page_title: document?.title,
});
setCurrentScreen(analytics, document.title ?? 'Undefined');
};
router.events.on('routeChangeStart', handleRouteChange);
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, [analytics, router.events]);
return <FirebaseContext.Provider value={analytics}>{props.children}</FirebaseContext.Provider>;
};
I can then consume it different pages or components:
const analytics = useContext(FirebaseContext);
// in sign up flow
logEvent(analytics, 'sign_up', {
uid: data.uid,
email: data.email,
});
Regarding the recapture erorr: NextJS will first attempt to render serverside content if there is any, before bootstrapping the react application. This means that the window has not been defined yet when you are trying to instantiate a new RecaptchaVerifier instance. You can use an if(window) to make sure you are only doing so when the window is instantiated, or alternatively, you can run a useEffect as follows:
useEfect(() => {
// This wont change on re renders
let completed = false;
if (!completed && window){
// recaptca instantiation
completed = true;
}
}, [window])

firebase.database(app) arg expects a FirebaseApp instance or undefined

I'm trying to set data to my realtime database on firebase. I have used the following code.
I am passing my database name as well as the region in my url still getting this error. Is there anyone who know's what is wrong with the code.
Error "firebase.database(app) arg expects a FirebaseApp instance or undefined.Ensure the arg provided is a Firebase app instance; or no args to use the default Firebase app." I have also initialised the firebase config.
Also I am getting the same problem while fetching data.
import {EMPLOYEE_UPDATE,EMPLOYEE_CREATE,} from './types';
import database from '#react-native-firebase/database';
import auth from '#react-native-firebase/auth';
import { firebase } from '#react-native-firebase/app';
import { Actions } from 'react-native-router-flux';
export const employeeUpdate = ({prop,value}) => {
return {
type: EMPLOYEE_UPDATE,
payload: {prop,value},
};
};
export const employeeCreate = ({name,phone,shift}) => {
const {currentUser} = auth();
return (dispatch) =>{
*const ref = database(
'https://managerproject-8924c-default-rtdb.asia-southeast1.firebasedatabase.app/')
.ref(`/users/${currentUser.uid}/employees`);
console.log(ref);
ref.set({name,phone,shift})
.then(()=> {*
console.log('Data set.');
dispatch({type: EMPLOYEE_CREATE });
Actions.employeeList({type: 'reset'});
});
};
};
As Firebase realtime database documentation,
So, the code will be:
import { firebase } from '#react-native-firebase/database';
firebase
.app()
.database('https://managerproject-8924c-default-rtdb.asia-southeast1.firebasedatabase.app/'))
.ref(`/users/${currentUser.uid}/employees`)
.set({name,phone,shift})
.then(() => console.log('Data set.'))
.catch((error) => console.log(error));

How to use 9.0.1 Firebase methods with VueJS 3

I'm fairly new to Vue and this is the second tutorial I'm following, which integrates firebase backend with Vue. But the tutorial is using Vue 2 and also an older version of firebase, so I thought I could try to do it with Vue 3 and the new Firebase version.
The resources on the firebase 9.0.1 seems to be fairly limited with regards to implementation with Vue at least. This is what I found from the firebase documentation regarding the signInAnonymously
import { getAuth, signInAnonymously } from "firebase/auth";
const auth = getAuth();
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
From what I understand, firebase 9.0.1 is an import only what you use style? so If I want to use the getAuth and signInAnonymously methods from the firebase/auth, I would do
import { getAuth, signInAnonymously } from 'firebase/auth';
But I am a bit confused as to how to use the methods in my .Vue file
so what I did in my firebase.js file was
export const auth = getAuth();
export {signInAnonymously};
then in my Login.vue file, i did
import { auth, signInAnonymously } from '../firebase'
export default {
data() {
return { auth }
},
methods: {
signInAnonymously
}
}
and I have a button that when clicked triggers the signInAnonymously, which is written like so
<button class="button" #click="signInAnonymously(auth)">Sign In</button>
What I have written seems to work, but I find it a bit convoluted/confusing and want to know
am I doing this correctly or is there a shorter/neater way to write the code?
what happens if I want to modify the signInAnonymously method as shown in the firebase documentation, i.e. adding those signInAnonymously(auth).then(() => {}), because if i were to add the arguments for the signInAnonymously in my export default like below, it doesn't recognize it as the exported method from my firebase.js file?
export default {
...,
methods: {
signInAnonymously(auth) {
...
}
}
Try creating a custom method and using signInAnonymously() within that as shown below:
import { auth } from '../firebase'
import { signInAnonymously } from 'firebase/auth'
// can be imported directly in Login.vue ^^
export default {
methods: {
anonymousLogin() {
// Directly pass 'auth' in this method
signInAnonymously(auth)
.then(() => {
// Signed in..
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ...
});
},
},
};
Then use this custom method in #click event:
<button class="button" type="button" #click="anonymousLogin">Sign In</button>

Firebase.firestore() is not a function?

We are trying to convert this json object timestamp:
Object {
"_nanoseconds": 725000000,
"_seconds": 1621386976,
}
to a firebase timestamp:
t {
"nanoseconds": 725000000,
"seconds": 1621386976,
}
Our code where the error is being thrown:
const lastItemIndex = thoughts.length - 1;
console.log(thoughts[lastItemIndex].date_created); // <--- logs Object timestamp
const seconds = thoughts[lastItemIndex].date_created._seconds;
console.log(seconds); // <--- logs seconds
const nanoseconds = thoughts[lastItemIndex].date_created._nanoseconds;
console.log(nanoseconds); // <---- logs nanoseconds
const lastDate = Firebase.firestore().Timestamp(seconds, nanoseconds); // <--- error
console.log(lastDate);
We are importing Firebase in our file like so:
import Firebase from '../../firebase';
And within the firebase.js file:
import * as firebase from 'firebase/app';
// Optionally import the services that you want to use
import 'firebase/firestore';
The warning we get:
[Unhandled promise rejection: TypeError: _firebase.default.firestore().Timestamp is not a function. (In '_firebase.default.firestore().Timestamp(seconds, nanoseconds)', '_firebase.default.firestore().Timestamp' is undefined)]
We have also tried the following:
const lastDate = new Firebase.firestore.Timestamp(seconds, nanoseconds);
and get the following error:
[Unhandled promise rejection: TypeError: undefined is not a constructor (evaluating 'new _firebase.default.firestore.Timestamp(seconds, nanoseconds)')]
We are following the docs to no avail. How can we convert this correctly?
Edit
exporting both Time_stamp and Firebase breaks the app [ the rest of the app does not recognize the Firebase export ]
export default Firebase makes everything back to normal. But the issue of converting the timestamp still remains
// Initialize Firebase
export const Firebase = firebase.initializeApp(firebaseConfig);
export const Time_stamp = firebase.firestore.Timestamp();
// export default Firebase;
The problem lies in how you are importing & exporting the library.
Reviewing your code
If this is where you are importing from the main library, you also need to make sure you are exporting it correctly. Looking at your current firebase.js file:
import * as firebase from 'firebase/app';
// Optionally import the services that you want to use
import 'firebase/firestore';
/* ... */
// Initialize Firebase
const Firebase = firebase.initializeApp(firebaseConfig);
export default Firebase; // <- this is a firebase.app.App not firebase itself
You are exporting an instance of firebase.app.App instead of firebase (the whole firebase library & namespace).
When you have an firebase.app.App instance, you can access Firestore of that app using app.firestore(). Because you import this app instance as Firebase in your main code, you confuse this with the normal firebase.firestore() which does something else.
To help illustrate the difference, take a look at this:
import * as firebase from "firebase/app";
import "firebase/firestore";
const config = { /* ... */ };
const defaultFirebaseApp = firebase.initializeApp(config);
// the instance of Firestore for the default app
const dbApp = defaultFirebaseApp.firestore();
// the instance of Firestore for the default app
const dbDefault = firebase.firestore();
// OR
// const dbDefault = firebase.firestore(dbApp);
console.log(dbApp === dbDefault); // -> true
const namedFirebaseApp = firebase.initializeApp(config, "something");
const dbNamedApp = namedFirebaseApp.firestore(); // returns instance of Firestore for the named app
// OR
// const dbNamedApp = firebase.firestore(dbNamedApp);
console.log(dbDefault === dbNamedApp); // -> false
Recommended export style
To properly export the Firebase library from firebase.js, you need to (and should) be using:
import firebase from 'firebase/app';
import 'firebase/firestore';
/* ... */
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase; // re-export firebase library & namespace
By re-exporting the library this way, you can use it in the same way as all the code samples you encounter:
import firebase from '../../firebase';
const {_nanoseconds, _seconds} = thoughts[lastItemIndex].date_created;
const dateCreatedAsTimestamp = new firebase.firestore.Timestamp(_nanoseconds, _seconds);
const db = firebase.firestore();
db.doc("collection/doc")
.set({
date_created: dateCreatedAsTimestamp
})
.then(
() => console.log("success"),
(err) => console.error("failed", err);
);
Alternative export style
If you intend to add some utility functions to firebase.js, the way you import stuff changes slightly
import firebase from 'firebase/app';
import 'firebase/firestore';
/* ... */
// Initialize Firebase
export const defaultApp = firebase.initializeApp(firebaseConfig);
export function castToTimestamp(timestampLikeObject) {
const {_nanoseconds, _seconds} = timestampLikeObject;
return new firebase.firestore.Timestamp(_nanoseconds, _seconds);
}
export default firebase; // re-export firebase library & namespace as the default
With the above file, you would instead import it as:
// you can import this normally like in the other example, but we'll
// include some of the other exports (like the utility function)
import firebase, { castToTimestamp } from '../../firebase';
const {_nanoseconds, _seconds} = thoughts[lastItemIndex].date_created;
const dateCreatedAsTimestamp = new firebase.firestore.Timestamp(_nanoseconds, _seconds);
// OR
// const dateCreatedAsTimestamp = castToTimestamp(thoughts[lastItemIndex].date_created);
const db = firebase.firestore();
db.doc("collection/doc")
.set({
date_created: dateCreatedAsTimestamp
})
.then(
() => console.log("success"),
(err) => console.error("failed", err);
);
The following works:
export const timestamp = firebase.firestore.Timestamp;
let bob = new timestamp();
console.log("bob, bob);
NOTE:
firebase.firestore.Timestamp()
NOT
firebase.firestore().Timestamp()
https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

Connection to Facebook with React and Firebase

i'm french, sorry for my little english.
I've a problem with Reactjs and Firebase, an error when i want connect with Facebook. I look tutorial in Udemy platform. This is a video for learn React
REBASE: The Firebase endpoint you are trying to listen to must be a string. Instead, got undefined
Parts of code Admin.js :
import React, { Component } from 'react'
import AjouterRecette from './AjouterRecette'
import AdminForm from './AdminForm'
import Login from './Login'
import firebase from 'firebase/app'
import 'firebase/auth'
import base, { firebaseApp } from '../base'
class Admin extends Component {
state = {
uid: null,
chef: null
}
componentDidMount () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.handleAuth({ user })
}
})
}
handleAuth = async authData => {
console.log(authData)
const box = await base.fetch(this.props.pseudo, { context: this })
if (!box.chef) {
await base.post(`${this.props.pseudo}/chef`, {
data: authData.user.uid
})
}
this.setState({
uid: authData.user.uid,
chef: box.chef || authData.user.uid
})
}
authenticate = () => {
const authProvider = new firebase.auth.FacebookAuthProvider()
firebaseApp
.auth()
.signInWithPopup(authProvider)
.then(this.handleAuth)
}
...
export default Admin
Thank's
Have a good day.
......................................................................................................................................................................................................................................................................................................................................................................................................
I've got exactly the same problem, probably because I follow the same training as you.
Your error is here :
const box = await base.fetch(this.props.pseudo, { context: this })
because this.props.pseudo is null.
in app.js, in the admin component, write
pseudo={this.props.match.params.pseudo}
and not
pseudo={this.state.pseudo}
and that shoudl work.
regards

Categories