Received an error stating "database.ref is not a function when working with vue 3."

I've been searching extensively, but I can't seem to make Firebase Realtime Database work for my web app. The goal is to manage products by adding, editing, viewing, and deleting them from a list. Below is the current code snippet from data.js. Any assistance would be greatly 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 fetchListings() {
    
    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/${listing.id}`)
      .set(listing);
  }
  
  export function emptyListing() {
    return {
      title: "",
      price: "",
      description: ""
    };
  }

Answer №1

It seems like there is some confusion between Firestore and the Realtime Database in Firebase. These two databases are separate entities with their own unique APIs.

The documentation provides clear guidance on how to get started with the Realtime Database and also discusses the usage of compat libraries in the upgrade process. To set up a database instance, you need to:

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

// Make sure to remove all Firestore imports and fine-grained imports

After that, initialize Firebase with your configuration:

firebase.initializeApp(firebaseConfig);

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with saving information to MongoDB

I recently started working with the MERN stack and I am trying to save user information in MongoDB, which includes two string attributes: "name" and "role". However, I encountered an error in the browser console stating "Failed to load resource: Request t ...

Transitioning to the Bootstrap library from the jQuery library with the use of several image modals

After coming across this specific question about implementing multiple image modals on a webpage, I noticed that it primarily focused on javascript and jQuery. However, my project involves utilizing the latest version of Bootstrap, so I'm curious if t ...

`Shuffle the order of Vue.js elements upon page load for a randomized effect`

I need help targeting specific elements using the ref attribute in Vuejs to randomize their order every time the page loads. The data is displayed in the template and managed in the component: <div class="team" > <div class="team__card" ref="c ...

Creating a dynamic `v-model` for computed properties that is dependent on the route parameter

I am creating a versatile component that can update different vuex properties based on the route parameter passed. Below is a simplified version of the code: <template> <div> <input v-model="this[$route.params.name]"/> </div&g ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

How can we make it simple for users to update webpage content using a file from their computer?

I am developing a custom application specifically for use on Firefox 3.6.3 in our internal network. My goal is to dynamically update the content of the page based on a file stored locally on my computer. What would be the most straightforward approach to ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Unusual vibrations experienced when using Orbit Controls to rotate the camera in Three.js

I am currently working on a project to create a model of the Solar System. Here is the metric I am using: scale = 0.001; // 1 unit - 1 kilometer var AU = 149597871 * scale; To set up the camera, renderer, and controls, I have defined them as follows: ca ...

Using a combination of different materials on a single mesh can lead to problems with z-index and clipping

Currently in my threejs project, I am attempting to apply two different materials to a mesh. One material has a solid color, while the other has a canvas texture. To achieve this, I have created both materials and added them to an array, which is then assi ...

The functionality of clicking on Google Visualization table chart to return row/column values is malfunctioning on Mozilla browser

I'm facing an issue with the code below that seems to behave differently in Chrome and Mozilla browsers. In Chrome, when a cell is clicked, the code successfully returns the row / column clicked. However, in Mozilla, clicking a cell does not trigger ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...

Achieving a jQuery event on elements that are generated dynamically, without the need to manually code

My issue is as follows: In my HTML, I am generating listings using JavaScript, with each listing structured like this: <div class="row" id="reveal-listing-id"> <div class="large-12 columns"> <div class="panel"> & ...

Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat ...

Angular: the page continues to display outdated information after using router.navigate

My web app allows users to select products to purchase. They can pause the configuration process and resume it later. Currently, I am using localStorage to store information about the products and their prices. There is a page in my app that displays a ta ...

Safari has no issues running Javascript, but other browsers are encountering failures

I am facing an issue where the code is working on Safari but failing on other browsers, and I can't figure out why. You can find the html part and the main javascript part. The main issue at hand is: When executing the function downloadurl(url, fun ...

At what point are watch variables accessible in the Chrome-Node-Debugger tool?

My test file runs periodically, either every minute or second, depending on how I configure it. https://i.sstatic.net/duXl5.png Despite setting watches on variables in the file, they do not populate as expected: https://i.sstatic.net/W6CFo.png Interest ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...