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

Transferring information submitted in a form to a service using AngularJS

Trying to implement a shopping cart app where I need to pass an object into a service function using Angular. Following advice from another post, but encountering an unprovided error and a strange syntax error on page load. The issues seem to be originatin ...

The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked: $http({ url: 'default.aspx/G ...

Leveraging functions in a Node.js module

I am struggling with using a function inside a Node.js module. I have implemented a custom sorting function to sort an array of objects based on the value of a specific property. exports.getResult = function(cards) { cards.sort(sortByField('suit& ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

What is the best way to combine two JSON objects?

Item A: var item1 = { "roleid": "001", "techid": "001", "role": "WEB DEVELOPER", "tech": "JAVASCRIPT", "experience": [], "certifications": [], "gender": ["Male"], "awards": [], "min_experience_years": "4", "max_expe ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

Looking to reset the default display option in a select dropdown using JavaScript or jQuery?

Here is some HTML code for a select element: <select> <br> <option>1</option><br> <option>2</option><br> </select> This select element will initially display the first option item (display ...

Limit access to route in ExpressJS only to internal redirects

I'm managing an ExpressJS application that includes specific routes which I intend to only function when redirected to from my code, rather than input directly into the URL. Essentially, if a user attempts to enter "myapp.com/url" it should not be ac ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Retrieve the value of a variable by using either an HTTP GET or POST request

Here's the HTML code snippet that I'm working with: <head> <h1>Sample Page</h1> </head> <body> <form method="POST" action=""> Enter Keyword <input type="text" name="key"> ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...

Creating JEST unit tests for a basic functionality

Here is the React code I have written: getDetails: function () { var apiUrl = ConfigStore.get('api') request .get(apiUrl) .set('X-Auth-Token', AuthStore.jwt) .set('Accept&apo ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Is there a way to modify the text color within the thumb-label of the Vuetify v-slider component?

Lately, I've been facing some challenges and my objective is to change the color of the thumb label on my v-slider to a custom one that is defined in the component's design. Can anyone provide guidance on how to achieve this? Regards, Joost ...

Navigating files using NodeJS and ExpressJS

Can NodeJS (or ExpressJS) facilitate the following task? Although I appreciate the flexibility that routing provides, I find the configuration process quite cumbersome. (I don't consider myself an expert in Express) For instance, imagine an applicat ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

Displaying multiple div elements when a button is clickedLet multiple divs be

ISSUE Hello there! I'm facing a challenge where I need to display a div when a button is clicked. The issue arises from having multiple divs with the same class, making it difficult for me to target each individual div... Image1 Image2 Desired Outco ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

The error message for ExpressJS states: "Headers cannot be set after they have already been sent."

Currently, I'm facing a challenge with ExpressJS and am having trouble finding the necessary documentation to resolve it. Technology Stack: body-parser: 1.17.0 express 4.15.0 multer: 1.3.0 MongoDB Postman The current view consists of 3 fields: n ...