简体   繁体   中英

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

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: ""
    };
  }

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'; // 👈

// 👆 Remove all Firestore imports, and all fine-grained improts

And then

firebase.initializeApp(firebaseConfig);

// Get a reference to the database service
var database = firebase.database();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM