skip to Main Content

No matter what I do, I always get the same result when trying to import Firebase Auth in React. As someone who is new to React, I am finding it difficult to figure out what the problem is and how to fix it. Despite my best efforts to try different importing methods, I am still getting the same output every time. It’s frustrating because I want to be able to move forward with my project, but this roadblock is slowing me down.

Error

./src/components/Register.js
  Line 13:  'firebase' is not defined  no-undef

Search for the keywords to learn more about each error.

Register.js

import React, { useState } from 'react';
import { auth } from '../firebase';


const Register = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);

  const handleRegister = async (e) => {
    e.preventDefault();
    try {
      await firebase.auth().createUserWithEmailAndPassword(email, password);
      setEmail('');
      setPassword('');
    } catch (error) {
      setError(error.message);
    }
  };


  return (
    <div>
      <h1>Register</h1>
      {error && <p>{error}</p>}
      <form onSubmit={handleRegister}>
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit">Register</button>
      </form>
    </div>
  );
};

export default Register;

firebase.js

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';

const firebaseConfig = {
  //project settings
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);

export { auth, db, storage };


if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

const firestoreNamespace = firebase.firestore

export {firebase, firestoreNamespace};

I’ve tried changing the import { auth } from '../firebase'; around but no help. I’m using node 16.10 if that helps.

2

Answers


  1. I don’t know how to help you exactly but in my project with firebase my firebase.json file looks like this:

    import { initializeApp } from 'firebase/app';
    import {
      getFirestore,
      collection,
      getDocs,
      addDoc,
      deleteDoc,
      serverTimestamp,
      doc,
      orderBy,
      limit,
      onSnapshot,
      query,
    } from 'firebase/firestore';
    import {
      getAuth,
      createUserWithEmailAndPassword,
      updateProfile,
      onAuthStateChanged,
      signInWithEmailAndPassword,
      signOut,
    } from 'firebase/auth';
    
    const firebaseConfig = {
      apiKey: "AIzaSyALfduQtADUHxMaELFidGT7aNaMcLs-SVo",
      authDomain: "tshirtsnew-a3e97.firebaseapp.com",
      projectId: "tshirtsnew-a3e97",
      storageBucket: "tshirtsnew-a3e97.appspot.com",
      messagingSenderId: "1020435418086",
      appId: "1:1020435418086:web:babd9ffdecb42a2a73e427",
      measurementId: "G-JZS9MSJX16"
    };
    
    // init firebase app
    initializeApp(firebaseConfig);
    
    // init services
    const db = getFirestore();
    const auth = getAuth();
    
    export {
      db,
      collection,
      getDocs,
      addDoc,
      deleteDoc,
      serverTimestamp,
      doc,
      auth,
      orderBy,
      limit,
      onSnapshot,
      query,
      createUserWithEmailAndPassword,
      updateProfile,
      onAuthStateChanged,
      signInWithEmailAndPassword,
      signOut,
    };

    And for authorization I used this:

    https://blog.gmagnenat.co/user-authentication-and-persistence-firebase-9-react-redux-toolkit
    
    Login or Signup to reply.
  2. You have declared firebase but you have not imported it hence why you are getting undefined.

    But I noticed you are using firebase v9 so you should not be using namespaces, instead you should use modular imports. Check the code below.

    //Register.js
    import React, { useState } from 'react';
    import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
    
    const Register = () => {
      const [email, setEmail] = useState('');
      const [password, setPassword] = useState('');
      const [error, setError] = useState(null);
      const auth = getAuth();
    
      const handleRegister = async (e) => {
        e.preventDefault();
        try {
          await createUserWithEmailAndPassword(auth, email, password)
          setEmail('');
          setPassword('');
        } catch (error) {
          setError(error.message);
        }
      };
     ...
    

    In your firebase.js file, i have removed the code after export since you have already initialized firebase.

    //firebase.js
    import { initializeApp } from 'firebase/app';
    import { getAuth } from 'firebase/auth';
    import { getFirestore } from 'firebase/firestore';
    import { getStorage } from 'firebase/storage';
    
    const firebaseConfig = {
      //project settings
    };
    
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const db = getFirestore(app);
    const storage = getStorage(app);
    
    export { auth, db, storage };
    

    Check documentation for more information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search