0

I am new to react and I am trying to connect to firebase in a class component and I get an error

Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app)

how to fix this?

code:

import React, { useRef, useState, Component } from 'react'
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { signOut } from 'firebase/auth';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/analytics';

const auth = firebase.auth();
const firestore = firebase.firestore();


class InfoLgn extends Component {
  render() {

      this.state = {
        user: null
      }

    firebase.initializeApp({
      apiKey: "xxxxxxxxxx",
      authDomain: "sssdsdsd.firapp.com",
      databaseURL: "https://xx-xx-default-rtdb.fireio.com",
      projectId: "xxx-d7287",
      storageBucket: "xxx-d7287.appspot.com",
      messagingSenderId: "xxxx",
      appId: "1:xxx:web:xxxx",
      measurementId: "G-xxxx"
    })

    return (
      <div>
         <div className="App">
        <header>
          <h1>⚛️</h1>
          <SignOut />
        </header>
       </div>
      </div>
    )
  }
}


function SignOut() {
  return auth.currentUser && (
    <button className="sign-out" onClick={() => auth.signOut()}>Sign Out</button>
  )
}


export default InfoLgn
James Z
  • 12,209
  • 10
  • 24
  • 44
BRDroid
  • 3,920
  • 8
  • 65
  • 143
  • Will the error persist if you move `firebase.initializeApp` block outside the class component and put it just before `const auth = firebase.auth();`? as `const app = firebase.initializeApp...`? I'd recomment to create a separate js/ts file `firebase.js` with firebase initialization code and auth/firestore export. – Sergey Sosunov Jan 08 '23 at 13:56
  • It's really not a good idea to initialize Firebase inside a component. Init should happen exactly once for the entire app before any other Firebase APIs are used. – Doug Stevenson Jan 08 '23 at 14:46

0 Answers0