简体   繁体   中英

Authentication with Firebase and Cloud Firestore

I am trying to figure out how to add authentication to a react app that uses Cloud Firestore rather than Realtime Database.

I followed this tutorial and got the whole thing working. Then - the change I'm trying to add is the move from Realtime Database to Cloud Firestore - this makes a difference to whether authentication works. I have made 20 new projects to try to get this work - totally without the process in the tutorial and just relying on firebase documentation . None of them work.

Currently, I have a config file with:

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import firestore from "firebase/firestore";

class Firebase {
  constructor() {
    app.initializeApp(config).firestore();
    this.auth = app.default.auth();
    // this.db = app.firebase.database()
    this.db = app.firestore();

  }  

Then, i have a form with this submit handler:

  import Firebase from '../../../firebase.1';

handleCreate = () => {
    const { form } = this.formRef.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      };
    const payload = {
    // ...values,
    name: values.name,
    email: values.email,
    organisation: values.organisation,
    beta: values.beta,
    role: values.role,
    // createdAt: Firebase.FieldValue.serverTimestamp()
    }
    console.log("formvalues", payload);

    Firebase
    .auth()
    .createUserWithEmailAndPassword(values.email, values.password)
    console.log('Received values of form: ', values);
    Firebase
    .collection("users")
    .add(payload)
    // .then(docRef => {
    //     resetForm(initialValues);
    // })
    .then(e => this.setState({ modalShow: true }))


    form.resetFields();
    this.setState({ visible: false });
    this.props.history.push(DASHBOARD);

  });

    };

At the moment, when I console.log(Firebase) I get:

Uncaught ReferenceError: Firebase is not defined

I have seen this post and followed each one of the recommendations in all of the answers.

I have tried changing the config file uses:

this.auth = app.default.auth();

It makes no difference.

When I try to use this, i get an error that says:

TypeError: _firebase_1__WEBPACK_IMPORTED_MODULE_14__.default.auth is not a function

Does anyone know how to use auth with firebase - where there is a Cloud Firestore instead of a Realtime Database - it's so weird that this makes a difference to whether the authentication tool works.

I've turned off the timestamp entry because I can't get firestore to record that either - but that is a problem for another day. I'm really trying to figure out how to use the authentication tool for now.

NEXT ATTEMPT

I tried to change the firebase.js file so that the config now looks like this:

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';


const devConfig = {

};

const prodConfig = {
};

const config =
  process.env.NODE_ENV === 'production' ? prodConfig : devConfig;


const Firebase = app.initializeApp(config);
const database = app.firestore();
const auth = app.auth();
const settings = { timestampsInSnapshots: true };


export { Firebase, database as default, settings, auth };

Now, I get an error that says:

TypeError: _components_firebase__WEBPACK_IMPORTED_MODULE_2__.default is not a constructor

I have been googling - what is a constructor. What is a webpack imported module number reference etc for the last few hours. I would love to know how to translate these error messages into something understandable.

Googling this exact error message suggests that something is wrong with the way the import and export statements are made. The new export in firebase.js is unusual (but others on Stack Overflow have tried it with problems using Firebase). It's still a question mark for me because I don't understand what the error message means.

The error message points to this line of my src/index.js

ReactDOM.render(

  <FirebaseContext.Provider value={new Firebase()}>

That line comes from:

import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase.1';
export default Firebase;
export { FirebaseContext, withFirebase };

That file imports from:

import React from 'react';
const FirebaseContext = React.createContext(null);

export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    {firebase => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);
export default FirebaseContext;

It would be a huge reveal if anyone has any advice for learning how to learn what error messages mean. For the moment I'm guessing.

I just finished the tutorial recently also, but I simplified my firebase file. I export only the reference to the initialised firebase

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

const config = {
  //...
};

const firebase = app.initializeApp(config);

export default firebase;

And in my project I have:

//...
import firebase from '../../firebase';
//...

useEffect(() => {
  const listener = firebase
    .firestore()
    .collection(COLLECTIONS.USERS)
    .onSnapshot(querySnapshot => {
      setUsers(querySnapshot);
      querySnapshot.forEach(doc => console.log(doc.id, doc.data()));
    });

  return listener;
}, []);
//...

Check out my Github project here -> https://github.com/henev/react-auth-with-firebase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM