The function call to 'import firebase.firestore()' results in a value

I recently set up a Vue App with the Vuefire plugin. Here is an example of my main.js file, following the documentation provided at: :

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { firestorePlugin } from 'vuefire'

Vue.config.productionTip = false;

Vue.use(firestorePlugin);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Additionally, I have another file called firebase.js structured like this:

import firebase from "firebase";

const config = {
    apiKey: "XXXXXX",
    authDomain: "XXXXX",
    databaseURL: "XXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXX",
    messagingSenderId: "XXXXXXX",
    appId: "XXXXX"
};

firebase.initializeApp(config);

export const db = firebase.firestore();

Lastly, here is a snippet from my home component:

<template>
  <div>
    <button @click="signIn">Log in with Google</button>
  </div>
</template>

<script>
import firebase from "firebase";
import db from "@/firebase"
export default {
  methods: {
    signIn() {
      const provider = new firebase.auth.GoogleAuthProvider();
      firebase
        .auth()
        .signInWithPopup(provider)
        .then(result => {
          const userDetails = {
            userId: result.user.uid,
            email: result.user.email,
            displayName: result.user.displayName,
            photoURL: result.user.photoURL
          };

          db.collection("users")
            .doc(result.user.uid)
            .set(userDetails, { merge: true });

        })
        .catch(err => console.log(err));
    }
  }
};
</script>

<style lang="scss" scoped>
</style>

An issue I encountered was when trying to use db.collection(...), I received the error:

TypeError: Cannot read property 'collection' of undefined

I found that changing db.collection(...) to

firebase.firestore().collection(...)
resolved the problem. However, I am curious as to why this change was necessary.

Answer №1

If you encounter a problem that requires importing specific dependencies separately, here is a safe method to do so:

import firebase from "firebase/app";
require('firebase/firestore')
require('firebase/auth')

const config = {
    apiKey: "XXXXXX",
    authDomain: "XXXXX",
    databaseURL: "XXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXX",
    messagingSenderId: "XXXXXXX",
    appId: "XXXXX"
};

firebase.initializeApp(config);

export const db = firebase.firestore();

export const auth = firebase.auth();

Afterward, your components can import them as shown below:

import firebase from 'firebase/app'
import { db, auth } from "./firebase" // <--- or wherever the config file is
export default {
  methods: {
    signIn() {
      const provider = new firebase.auth.GoogleAuthProvider();
       auth
        .signInWithPopup(provider)
        .then(result => {
          const userData = {
            userId: result.user.uid,
            email: result.user.email,
            displayName: result.user.displayName,
            photoURL: result.user.photoURL
          };

          db.collection("users")
            .doc(result.user.uid)
            .set(userData, { merge: true });

        })
        .catch(err => console.log(err));
    }
  }
};

I hope this explanation is clear and beneficial!

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

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

Updating the list in React upon form submission without requiring a full page refresh

Currently, I have a list of data being displayed with a specific sort order in the textbox. Users are able to modify the order and upon clicking submit, the changes are saved in the database. The updated list will then be displayed in the new order upon pa ...

Having trouble parsing an array from req.body using Node.js Express

I am currently facing an issue while trying to retrieve an array from a JSON request using Postman. In my Node.js application, I am able to read all values from req.body except for the array. When attempting to access the array, I only receive the first va ...

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

Labels can sometimes cause text input fields to become unresponsive

I've encountered a bug while working on my website with the materializecss framework. Sometimes, inputs are not responding correctly. This issue seems to occur when clicking on the first input and accidentally targeting the higher part of the second ...

Tips for utilizing the form.checkValidity() method in HTML:

While delving into the source code of a website utilizing MVC architecture, I encountered some difficulties comprehending it fully. Here is a snippet of the view's code: function submitForm (action) { var forms = document.getElementById('form& ...

Trouble with the x-cloak attribute in alpine.js

Experience with TailwindCSS and AlpineJS in my current project has brought to my attention a slight issue with the header dropdowns flashing open momentarily when the login page loads. I attempted to use x-cloak to address this, but encountered some diffic ...

How is UI Router Extras causing unexpected errors in my unit tests?

QUESTION: - I am facing failures in my tests after installing ui-router-extras. How can I resolve this issue? - Is there a way to use ui-router-extras without causing test failures? If you want to quickly install this, use yeoman along with angular-full ...

Counting JSON Models in SAP UI5

I am encountering a particular issue. Please forgive my imperfect English. My goal is to read a JSON file and count the number of persons listed within it. I want this result to be stored in a variable that is linked to the TileContainer. This way, whenev ...

What is the method for accessing a marker from beyond the map on OpenStreetMap?

Recently, I made the switch from using Google Maps to OpenStreetMap in my project due to the request limit constraints imposed by Google. My client needed a higher request limit, but was unable to afford the costs associated with increasing it on Google Ma ...

How can I create space between a checkbox and its label in Google Web Toolkit (GWT)?

How can I create space between a Checkbox and its content in GWT? Checkbox c = new Checkbox("checkme"); c.setStyleName("checkbox_style"); When I try using padding or margin, the entire checkbox and its content move together. Is there a way to achieve a g ...

Wheelnav.js implementing a dynamic bouncing animation

I'm currently in the process of working on a pie menu with wheelnav.js and everything is going smoothly so far. However, I can't seem to find any information in the wheelnav.js documentation on how to eliminate the bouncing effect when a menu cho ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

Using jQuery to assign a specific value to all select boxes

I am facing a challenge where I need to change the values of all select boxes on my page to a specific number. Here is the HTML structure: <select> <option value="-1" <option value="55">ENABLE</option> <option value= ...

Using Angular to display exclusively the selected items from a list of checkboxes

Is there a way to display only the checked items in a checkbox list? I am looking for a functionality where I can select multiple items from a checkbox list and then have an option to show only the selected items when needed, toggling between showing just ...

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files. To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing ...

Refreshing a webpage following an AJAX call

Whenever I make a post request to an API, I receive a response. However, even though the data is saved when I hit the API, I have to manually refresh my blade.php page to see the newly added data. Is there a way to automatically update my blade with the ...

Preventing opening while closed through the OnClick event

I have the following OnClick function: const [open, setOpen] = useState(true); and onClick={() => setOpen(!open != true)} The goal is to "close when open" and "remain closed if already closed". The current code achieves the second part but not the fir ...