Using Vue to send information to Firebase

I could really use some assistance. Despite my best efforts over the past few days, and despite watching numerous tutorials and consulting various methods in Firebase documentation, I am still unable to make any progress.

My current project involves building a Vue chat application and attempting to write data into Firebase databases. The contents of my firebase/init.js file are as shown below:

import { initializeApp } from "firebase/app";
import { getFirestore} from 'firebase/firestore';

const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  projectId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
  measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
};


const app = initializeApp(firebaseConfig);

const db = getFirestore(app);

export default db;

The scripting section of my CreateMessage.vue file is outlined below:

<script>
import {collection, addDoc} from "firebase/firestore";
export default {
    name: 'CreateMessage',
    props: ['name'],
    data() {
        return {
            newMessage: null,
            errorText: null
        }
    },
    methods: {
        createMessage () {
            if (this.newMessage != "") {
                addDoc(collection(firestore, "messages"),{
                    message: this.newMessage,
                    name: this.name,
                    timestamp: Date.now()
                });
                this.newMessage = null;
                this.errorText = null;
            } else {
                this.errorText = "A message must be entered first!";
            }
        }
    }    
}
</script>

Any guidance or advice on this matter would be immensely appreciated. Thank you all for your help in advance.

Answer №1

In order to properly utilize your init.js file, ensure that you are correctly importing the 'db' variable into your component. To do this, make sure to add:

import { db } from 'firebase/init.js

After importing 'db', proceed by adding the doc using the following code snippet:

addDoc(collection(db, 'messages'), ...

Alternatively, if you prefer not to import 'db', you can also import 'getFirestore' from 'firebase/firestore' and use it in the following way:

addDoc(collection(getFirestore(), 'messages'), ...

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

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

Struggling to pass data while converting Vue slot code to React slot code. Can someone help me out?

https://codepen.io/mic1/project/editor/ANwjrN Sample Vue code for skeleton framework... <SiteHeader> <Dropdown> <template id="trigger" #trigger="{ hasFocus, isOpen }"> <span class="block":clas ...

Having trouble viewing objects' content in the JavaScript console in Visual Studio 2015?

In the past, I was able to see all the content of my JavaScript objects like this: However, for some reason now, the content is not being displayed at all: I am using Visual Studio 2015 Community with Cordova and Ripple emulator. I have tried creating a ...

React Native SectionList Divided by Dates

I have a task to reformat my date object where I have an array of dates in the following format: Object { "FREETIME": "2021-04-19 11:30:00", }, Object { "FREETIME": "2021-04-19 12:00:00", }, Object ...

The loading sequence of Vuetify CSS for buttons is inconsistent in the production build, leading to functionality problems

I am currently working on a Vue application that utilizes a Vuetify "bottom navigation" component as shown below: <v-bottom-navigation app fixed grow color="#121212" class="bottom-navigation" > <v-btn text tile v-for="menuI ...

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

Mongoose issue with updating a field within a subarray object

I'm facing some issues while updating a field in my mongoose model. My intention is to locate a specific username within a list of friends in a user model and then proceed to update a field within the same object that contains the corresponding userna ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

The npm operation completed successfully, however the terminal process came to a halt due to reaching the

I've been diving into learning Vue js and encountered a strange issue when attempting to run npm run watch. Initially, it shows Build successfully, but then the terminal process abruptly stops with an error message: Error from chokidar (/var/www/htm ...

The child div can be scrolled horizontally, while the parent window remains fixed

I am facing a challenge with my HTML and CSS setup. I want to create a child div that scrolls horizontally, but I do not want the parent window to scroll along with it. Below is my current code: <div id="parent"> <div id="div1"> . ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Vue.js and the flexibility of component paths

I decided to break up my vuejs application into components, but whenever I make updates to the architecture, it becomes a challenge to adjust the component paths accordingly. To simplify maintenance, I am attempting to store the component path in a setting ...

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Learn how to use props in React with the PluralSight tutorial - don't forget to

While working through a React tutorial on PluralSight, I encountered an error that I'm not sure is my mistake or not. The tutorial directed me to the starting point at JS Complete using this URL: As I followed along, the tutorial led me to the follo ...

Combining a group of JavaScript objects

I am facing a challenge with my collection as I need to perform aggregation using only JavaScript. I have attempted various approaches utilizing the Lodash library but unfortunately, I have not been successful. If you could provide me with some guidance on ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

Incorporating Card Layouts with SwiperJS

Reference Code: See Example on Code Sandbox I am looking to implement a swiper that allows for navigating one slide at a time with a layout where slidesPerView: "auto" and fixed width are used. The first two slides behave as expected, but the la ...

VUE3 - Trigger Bootstrap Modal with Image Click on Multiple Pages/Components Without the Use of JQuery

Attempting to integrate VUE3 and Bootstrap for the purpose of opening a Modal upon clicking one of two images. I have organized my project into 3 Components: Left DIV (Image) Right DIV (Image) Modal While successful in operating this feature on a Singlep ...

The issue with Flutter Firebase FCM notifications consistently displays a bland white/grey square instead of the desired custom app icon

Even after trying all the advice from Stackoverflow, no difference was seen: Adding this code to the AndroidManifest <application android:name="io.flutter.app.FlutterApplication" android:label="Honest" android:icon="@mipmap/ic_launcher"> ...