Home > Mobile >  Uncaught TypeError: database.ref is not a function using vue 3
Uncaught TypeError: database.ref is not a function using vue 3

Time:06-06

I've spent a good few hours searching around here but nothing wanted to work. I want to use firebase realtime database but whatever I try, I just keep getting errors. The aim of this webapp is to add, edit, view and delete products from a list. This is what I have in the data.js so far. Any help would be appreciated :)

import firebase from 'firebase/compat/app';
import store from "./store";
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/database';
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    databaseURL: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};
  
const app = initializeApp(firebaseConfig);
const database = getFirestore();

export default function setListingData() {
    
    database.ref("/listings")
      .get()
      .then(function(snapshot) {
        if (snapshot.exists()) {
          let listings = [];
          snapshot.forEach((e) => {
            listings.push(e.val());
          });
          console.log(listings);
  
          store.commit("initListings", listings);
  
          return snapshot.val();
        } else {
          console.log("No data available");
        }
      })
      .catch(function(error) {
        console.error(error);
      });
  }
  
  export function deleteListing(id) {
    firebase
      .database()
      .ref(`/listings/${id}`)
      .remove();
  }
  
  /**
   * Add/edit listing
   * @param {*} listing The listing
   */
  export function addListing(listing) {
    console.log("ADDING:", listing);
    firebase
      .database()
      .ref(`/listings/${listings.id}`)
      .set(listings);
  }
  
  export function emptyListing() {
    return {
      title: "",
      price: "",
      description: ""
    };
  }

CodePudding user response:

You're mixing up Firestore and the Realtime Database here. While both databases are part of Firebase, they are completely separate and each has its own API.

As shown in the documentation on getting started with the Realtime Database and in the section on using the compat libraries, you get a database instance with:

import firebase from 'firebase/compat/app';
import store from "./store";
import 'firebase/compat/auth';
import 'firebase/compat/database'; //            
  • Related