Experiencing a glitch with the Realtime Database feature on Firebase

    // db.js file

    import * as firebase from "firebase/app"
    import "firebase/database"

    const config = {
        apiKey: "" ...
    }

    const db = firebase.initializeApp(config)
    export default db

    // App.vue file


    import { reactive, onMounted, ref } from 'vue'
    import db from "./db.js";

    const SendMessage = () => {
          const messagesRef = db.database().ref("messages")

          if(inputMessage.value === "" || inputMessage.value === null) {
            return
          }

          const message = {
            username: state.username,
            content: inputMessage.value
          }

          messagesRef.push(message)
          inputMessage.value = ""
        }

I am working on a chat application using Vue.js and Firebase. However, I encountered an issue when trying to send a message: db_js__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function at Proxy.SendMessage (App.vue?3dfd:63:1)

I suspect the problem lies in the way I imported the database module, but even after attempting to switch to version 9 of Firebase, the error persists.

Answer №1

Firebase V9 embraces a functional approach, which is evident in the way Firestore interactions are handled. I typically receive an indicator if something isn't functioning as expected.

db.js

import { initializeApp } from 'firebase/app';
import { getDatabase, ref, push, child, serverTimestamp } from 'firebase/database'

const config = {
  apiKey: "" ...
}

const firebase = initializeApp(config)
const db = getDatabase()

function addMessage(path, message) {
  message.createAt = serverTimestamp() // The database will automatically assign the current timestamp to this field for sorting purposes.
  return push(child(ref(db, path)), message)
}
export { addMessage }

App.vue file

import { reactive, onMounted, ref } from 'vue'
import { addMessage } from "./db.js";

const SendMessage = async () => {
  if (!inputMessage.value) return 
  // The above line checks if the value is empty or null by returning false and using ! to convert it to true.

  const message = {
    username: state.username,
    content: inputMessage.value
  }

  const result = await addMessage('path to data in tree', message)
  // The async/await syntax ensures that the code waits for the data to be saved in the database before proceeding.
  console.log(result.key) // If awaited, the result can be accessed if it's not void.
  inputMessage.value = ""
}

If you're using ref() in .vue files, remember that database operations outside of vue files utilize the same ref() function but with different functionality. You also have the option to rename functions during import like so:

import { ref as dbRef } from '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

What steps can I take to prevent Internet Explorer from caching my webpage?

After implementing Spring MVC for Angular JS on the front end, I encountered an issue where logging in with different user credentials resulted in incorrect details being displayed. This problem only occurred in Internet Explorer, requiring me to manually ...

Tips for accessing a composition function in VueJS from another composition

I've been diving into the new composition-api within VueJS and have encountered a problem that I need help with. I am seeking advice on how to effectively tackle this issue. Previously, when everything was vuex-based, dispatching an action to another ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...

Managing multiple carousels simultaneously using the middle mouse button in Swiper.js

I am currently utilizing 5 carousels on my screen, all of which are operated by the same navigation buttons. In addition to this, I require the ability to control them using the middle mouse scroll. However, when I activate the mouse wheel control, only ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

Center-align the table element

I've been struggling to center align this table element, specifically the one containing the square, but nothing seems to be working. Can anyone lend a hand in fixing this issue? <table> <tbody> <tr> <td>TURKEY - SU ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...

What is the best way to preload all videos on my website and across different pages?

I specialize in creating video websites using HTML5 with the <video> tag. On my personal computer, the website transitions (fadeIn and fadeOut) smoothly. However, on my server, each page seems to take too long to load because the videos start preloa ...

Creating an HTML file using PUG in a local environment (using npm and gulp)

Is there a way to automatically generate an HTML file with the same name as my Pug file whenever I save using gulp? I've checked all the documentation on but it only explains how to return Pug content in console... ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

Tips for navigating the world of hybrid web applications that combine elements of both traditional multi-page applications and single-page

What are some best practices for developing a multi-page application using modern JavaScript frameworks? Multi-page Application In a multi-page application, we utilize multiple templates with "template syntax" to retrieve backend data and handle AJAX (if ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) { var tipPercent; if (bill < 50 ) { tipPercent = .20; } else if (bill >= 50 && bill < 200){ tipPercent = .15; } else { tipPercent = .10; } return tipPercent * bill; } var bills = ...

Wordpress is having issues running jQuery

I've developed a function inside js/custom.js. The purpose of this function is to arrange posts in my Wordpress site by applying a class called articleAlign. This class will enhance the spacing between the article title and its excerpt, but only when ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...