I'mnew
I'mnew

Reputation: 11

Error - Cannot read property 'initializeApp' of undefined

I'm creating a social app and I got this error. What should I do?

This is my config file:

import * as firebase from "firebase/app";

const FirebaseKey = { 

   apiKey: "****",
   authDomain: "****",
   databaseURL: "****",
   projectId: "****", 
   storageBucket: "****",
   messagingSenderId: "****", 
   appId: "****" 

};


export default !firebase.apps.length ? firebase.initializeApp(FirebaseKey) : firebase.app();

And this is my Fire.js file's beginning (here is the mistake):

import FirebaseKeys from "./Config";
import firebase from "./App";
require("firebase/firestore");

class Fire {
    constructor() {
        firebase.initializeApp(FirebaseKeys);
    }

Upvotes: 1

Views: 4045

Answers (3)

criss_dev
criss_dev

Reputation: 81

Firebase 8 introduced some breaking changes.

https://firebase.google.com/support/release-notes/js#version_800_-_october_26_2020

Now you can make it work like this if you use .default:

const firebase = require('firebase/app').default

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

Upvotes: 1

ADITYA AHLAWAT
ADITYA AHLAWAT

Reputation: 166

In firebase 8.0.0 and above it is

import firebase from 'firebase'

and for firebase <8.0.0

it is

import * as firebase from 'firebase'

Upvotes: 3

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

You're exporting a FirebaseApp instance, and not the firebase namespace that surrounds it. So with your current config file, you:

  1. Don't have to call firebase.initializeApp(FirebaseKeys); in your Fire.js anymore.
  2. Can access the services directly from your import: firebase.firestore().

But I'd recommend exporting the firebase namespace:

import * as firebase from "firebase/app";

const FirebaseKey = { 

   apiKey: "****",
   authDomain: "****",
   databaseURL: "****",
   projectId: "****", 
   storageBucket: "****",
   messagingSenderId: "****", 
   appId: "****" 

};

if (!firebase.apps.length) firebase.initializeApp(FirebaseKey)

export default firebase;

And then:

import FirebaseKeys from "./Config";
import firebase from "./App";
require("firebase/firestore");

class Fire {
    constructor() {
        firebase.firestore()... // access the database
    }

Upvotes: 1

Related Questions