Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error:

Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function

The versions I am using are: "firebase": "^9.0.0" "vue": "^3.0.0"

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";


const firebaseConfig = {
// keys
};

const app = initializeApp(firebaseConfig);

const db = getDatabase(app);

export {db}

Here is my function call:

import {reactive} from 'vue';
import { ref, set, push } from "firebase/database";
import {db} from "./db"


export default {
  setup(){
    const inputUsername = ref("");
    const inputMessage = ref("");
    const state = reactive({
        username: "",
        messages:[]
    });

    const Login = () =>{
      if(inputUsername.value != "" || inputUsername.value != null){
       state.username = inputUsername.value;
       inputUsername.value = "";
      }
    }
    const SendMessage = () => {
    //   const messagesRef = db.database().ref("messages");
      if (inputMessage.value === "" || inputMessage.value === null) {
        return;
      }
      const message = {
        username: state.username,
        content: inputMessage.value
      }
      set(push(ref(db, 'messages')), message);

    //   messagesRef.push(message);
      inputMessage.value = "";
    }
    return{
    inputUsername,
    Login,
    state,
    inputMessage,
    SendMessage
    }
  }
}

I have attempted to resolve this issue by following the suggestions provided, but unfortunately, it did not work.

Thank you!

Answer №1

The updated modular SDK no longer utilizes namespaces, meaning you can't use app.database(). Instead, export a database instance from the file where Firebase is initialized like this:

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const app = initializeApp(firebaseConfig);

const db = getDatabase(app);

export {db}

Then import it wherever needed and use it as follows:

import { ref, child, get } from "firebase/database";
import {db} from "../path/to/firebase.js"

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

set(push(ref(db, 'messages')), message);

To learn more about the new syntax, refer to the documentation


Uncaught TypeError: db._checkNotDeleted is not a function

This error occurs when importing ref from both firebase and vue. Make sure to import Firebase's ref as fireRef.

import { reactive, ref } from "vue";
import { ref as fireRef, set, push } from "firebase/database";
import { db } from "./db";

// usage 
set(push(fireRef(db, "messages")), message);

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

Activate fullscreen mode in Krpano on desktop by clicking a button

Is there a way to activate fullscreen mode upon clicking a button? I believe I should use the code: krpano.set(fullscreen,true); Currently, I have an image within a slideshow that includes a play button overlay. Once the button is clicked, the slideshow ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

I recently discovered how to modify the video source (src) within an html5 source tag, but I am encountering varied outcomes when using it within a function or with inline javascript

When attempting to change the src of a video tag using Javascript, I encountered an issue. The code works fine when placed inline, but as soon as I try to include it within a function or in the "onclick" event of a button tag, nothing happens. There are no ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

Attempting to utilize Vue js to connect to an API

I'm currently facing difficulties while trying to access an API in order to retrieve data. As a novice in the world of vue.js and javascript, I encountered an error message saying Uncaught SyntaxError: Invalid shorthand property initializer. Unfortuna ...

Encountering a CORS error in my Next.js 13.4 application while attempting to retrieve JSON data

Here is the location of the actual fetch request in our search/page. import { useSearchParams } from "next/navigation"; import Footer from "../components/Footers"; import Header from "../components/header"; import { format } ...

Error with YouTube API in Internet Explorer 8: Video not found

While using the iframe youtube api to handle video, everything runs smoothly on Chrome and Firefox. However, when trying to implement it on Internet Explorer 8, an error saying 'video' is undefined pops up. Any suggestions on how to resolve this ...

Step-by-step guide to showing the contents of every file in a directory on the console using node.js or express

Having trouble retrieving file contents from a folder using Node.js I can successfully retrieve the contents of one file using the read function, but unable to retrieve contents of all files at once. ...

Shifting attention from the main point to the surrounding details (including siblings)

In my search bar layout, the main parent component consists of three child components - location dropdown, date picker (calendar), and duration dropdown. By default, the user's location is pre-selected in the location dropdown. I want the focus to shi ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

I intend to use the v-for directive in Vue to create a table

Below is an example of a JavaScript array. mydata:[1,2,3,4,5,6,7,8,9] This is the desired result in table format: 1 2 3 4 5 6 7 8 9 Using vanilla HTML, you can achieve this with a table: <table> <tr> <td>1</td><td>2& ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

The json_decode function in PHP unexpectedly returns null when provided with valid JSON input

I am attempting to send a JSON object using AJAX post in JavaScript as shown below: $.ajax({ type: 'POST', url: 'testPost.php', data: {json: cond}, dataTyp ...

Tips for showcasing JSON data within an array of objects

I'm trying to work with a JSON file that has the following data: {"name": "Mohamed"} In my JavaScript file, I want to read the value from an array structured like this: [{value: "name"}] Any suggestions on how I can acc ...

JS form validation malfunctioning

XHTML <form name="suggestion" method="post" action="suggestion.php" class="elegant-aero" onSubmit="return validate()" > <label> <span>Message :</span> <textarea id="Message" name="m ...

When using the `sendFile` method in Node.js Express, you will notice that the HTML content

Hey there, I'm new to nodejs and trying to create a simple website with two pages. I'm facing an issue where the content of the second file is being rendered as the first one, even though the source inspector in the browser indicates that it&apos ...