Gary Zlobinskiy
Gary Zlobinskiy

Reputation: 93

No Firebase App '[DEFAULT]' has been created Error when trying to build private messaging system

I am building a private messaging system for a React Native App, but I can not fix an error that is present in my expo app. The error is:

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

The code is:

import FirebaseKeys from "./config";
import firebase from "firebase";
require("firebase/firestore");
import { COLLECTIONS } from './constants'

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

    auth = firebase.auth();

    firestore = firebase.firestore();

    messageRef = this.firestore.collection(COLLECTIONS.MESSAGES);

    async signIn() {
      try {
        const response = await this.auth.signInAnonymously();
        return {user: response.user };
      } catch (error) {
        return { error };
      }
    }

    async fetchMessages() {
      const messages = await this.messageRef
        .orderBy('created_at', 'desc')
        .limit(10)
        .get();

      return messages.docs;
    }

    async createMessage({ message, uid }) {
      await this.messageRef.add({
        message,
        user_id: uid,
        created_at: new Date()
      })
    }

    createAndSendMessage = async ({ message, avatar, receiverId, image }) => {
      return new Promise((res, rej) => {
        this.firestore
          .collection("messages")
          .add({
            message: message,
            avatar: avatar,
            senderId: (firebase.auth().currentUser || {}).uid,
            receiverId: receiverId,
            image: image,
            timestamp: firebase.database.ServerValue.TIMESTAMP
          }).then(ref => {
            res(ref);
          })
          .catch(error => {
            ref(error);
          });
      });
    };

    addPost = async ({ text, localUri }) => {
        const remoteUri = await this.uploadPhotoAsync(localUri, `photos/${this.uid}/${Date.now()}`);

        return new Promise((res, rej) => {
            this.firestore
                .collection("posts")
                .add({
                    text: text,
                    uid: this.uid,
                    timestamp: this.timestamp,
                    image: remoteUri
                })
                .then(ref => {
                    res(ref);
                })
                .catch(error => {
                    rej(error);
                });
        });
    };

    uploadPhotoAsync = (uri, filename) => {
        return new Promise(async (res, rej) => {
            const response = await fetch(uri);
            const file = await response.blob();

            let upload = firebase
                .storage()
                .ref(filename)
                .put(file);

            upload.on(
                "state_changed",
                snapshot => {},
                err => {
                    rej(err);
                },
                async () => {
                    const url = await upload.snapshot.ref.getDownloadURL();
                    res(url);
                }
            );
        });
    };

    createUser = async user => {
        let remoteUri = null;

        try {
            await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);

            let db = this.firestore.collection("users").doc(this.uid);

            db.set({
                name: user.name,
                email: user.email,
                avatar: null
            });

            if (user.avatar) {
                remoteUri = await this.uploadPhotoAsync(user.avatar, `avatars/${this.uid}`);

                db.set({ avatar: remoteUri }, { merge: true });
            }
        } catch (error) {
            alert("Error: ", error);
        }
    };

    off() {
      this.db.off();
    };

    get db() {
      return firebase.database().ref("messages");
    }

    get uid() {
      return (firebase.auth().currentUser || {}).uid;
    }

    signOut = () => {
        firebase.auth().signOut();
    };

    get firestore() {
        return firebase.firestore();
    }

    get uid() {
        return (firebase.auth().currentUser || {}).uid;
    }

    get name() {
      return firebase.auth().currentUser;
    }

    get email() {
      return firebase.auth().currentUser.email;
    }

    get avatar() {
      return firebase.auth().currentUser.avatar;
    }

    get timestamp() {
        return Date.now();
    }
}

Fire.shared = new Fire();
export default Fire;

Any help would be largely appreciated. Thank you in advance! (Also, if you happen to know any tutorials on how to build private messaging with react native and firebase, please let me know as I am struggling with the entire task.)

Upvotes: 0

Views: 125

Answers (1)

Phix
Phix

Reputation: 9910

You need to move the following lines-

auth = firebase.auth();
firestore = firebase.firestore();
messageRef = this.firestore.collection(COLLECTIONS.MESSAGES);

...explicitly inside the constructor after the firebase.initializeApp line. When TypeScript transpiles it places those lines before the initialization which doesn't work.

Upvotes: 1

Related Questions