javascript - TypeError: Cannot read properties of undefined (reading 'collection') - Vuejs and Firebase - Stack

I'm trying to develop a calendar that will contain tasks. I'm trying to use firebase, but it

I'm trying to develop a calendar that will contain tasks. I'm trying to use firebase, but it keeps giving an error saying it doesn't understand the 'collection()' property. I've already researched a lot of things, tried to do it in other ways, but I didn't get anything. I can register if I do otherwise, but reading the data with the 'collection', no. Detail I'm using version 9 of firebase

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'collection')

I don't know what else to do, can someone help me please? The entire script is below.

Script

export default {
  data: () => ({
    today: new Date().toISOString().substr(0, 10),
    focus: new Date().toISOString().substr(0, 10),
    type: 'month',
    typeToLabel: {
      month: 'Month',
      week: 'Week',
      day: 'Day',
      '4day': '4 Days',
    },
    name: null,
    details: null,
    start: null,
    end: null,
    color: '#1976D2', // default event color
    currentlyEditing: null,
    selectedEvent: {},
    selectedElement: null,
    selectedOpen: false,
    events: [],
    dialog: false
  }),
  mounted () {
    this.getEvents()
  },
  puted: {
    title () {
      const { start, end } = this
      if (!start || !end) {
        return ''
      }
      const startMonth = this.monthFormatter(start)
      const endMonth = this.monthFormatter(end)
      const suffixMonth = startMonth === endMonth ? '' : endMonth
      const startYear = start.year
      const endYear = end.year
      const suffixYear = startYear === endYear ? '' : endYear
      const startDay = start.day + this.nth(start.day)
      const endDay = end.day + this.nth(end.day)
      switch (this.type) {
        case 'month':
        return `${startMonth} ${startYear}`
        case 'week':
        case '4day':
        return `${startMonth} ${startDay} ${startYear} - ${suffixMonth} ${endDay} ${suffixYear}`
        case 'day':
        return `${startMonth} ${startDay} ${startYear}`
      }
      return ''
    },
    monthFormatter () {
      return this.$refs.calendar.getFormatter({
        timeZone: 'UTC', month: 'long',
      })
    }
  },
  methods: {
    async getEvents () {
      let snapshot = await dbStore.collection('calEvent').get()
      const events = []
      snapshot.forEach(doc => {
        let appData = doc.data()
        appData.id = doc.id
        events.push(appData)
      })
      this.events = events
    },
    setDialogDate( { date }) {
      this.dialogDate = true
      this.focus = date
    },
    viewDay ({ date }) {
      this.focus = date
      this.type = 'day'
    },
    getEventColor (event) {
      return event.color
    },
    setToday () {
      this.focus = this.today
    },
    prev () {
      this.$refs.calendar.prev()
    },
    next () {
      this.$refs.calendar.next()
    },
    async addEvent () {
      if (this.name && this.start && this.end) {
        await dbStore.collection('calEvent').add({
          name: this.name,
          details: this.details,
          start: this.start,
          end: this.end,
          color: this.color
        })
        this.getEvents()
        this.name = '',
        this.details = '',
        this.start = '',
        this.end = '',
        this.color = ''
      } else {
        alert('You must enter event name, start, and end time')
      }
    },
    editEvent (ev) {
      this.currentlyEditing = ev.id
    },
    async updateEvent (ev) {
      await dbStore.collection('calEvent').doc(this.currentlyEditing).update({
        details: ev.details
      })
      this.selectedOpen = false
      this.currentlyEditing = null
      this.getEvents()
    },
    async deleteEvent (ev) {
      await dbStore.collection('calEvent').doc(ev).delete()
      this.selectedOpen = false
      this.getEvents()
    },
    showEvent ({ nativeEvent, event }) {
      const open = () => {
        this.selectedEvent = event
        this.selectedElement = nativeEvent.target
        setTimeout(() => this.selectedOpen = true, 10)
      }
      if (this.selectedOpen) {
        this.selectedOpen = false
        setTimeout(open, 10)
      } else {
        open()
      }
      nativeEvent.stopPropagation()
    },
    updateRange ({ start, end }) {
      this.start = start
      this.end = end
    },
    nth (d) {
      return d > 3 && d < 21
      ? 'th'
      : ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'][d % 10]
    }
  }
}

Main

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import vuetify from './plugins/vuetify'

// Firebase
import firebase from 'firebase/pat/app';
import 'firebase/pat/firestore';

//I have initialized my project with valid values but mented the keys to avoid publishing them online.
firebase.initializeApp({
  apiKey: "<my_api_key>", 
  authDomain: "<my_project_domain>",
  projectId: "<my_project_id>",
  databaseURL: "",
  storageBucket: "<my_project_storage_bucket>",
  messagingSenderId: "<my_messaging_sender_id>",
  appId: "<my_app_id>",
  measurementId: "<my_measurement_id>"
});

Vue.config.productionTip = false

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


export const dbStore = firebase.firestore();

I'm trying to develop a calendar that will contain tasks. I'm trying to use firebase, but it keeps giving an error saying it doesn't understand the 'collection()' property. I've already researched a lot of things, tried to do it in other ways, but I didn't get anything. I can register if I do otherwise, but reading the data with the 'collection', no. Detail I'm using version 9 of firebase

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'collection')

I don't know what else to do, can someone help me please? The entire script is below.

Script

export default {
  data: () => ({
    today: new Date().toISOString().substr(0, 10),
    focus: new Date().toISOString().substr(0, 10),
    type: 'month',
    typeToLabel: {
      month: 'Month',
      week: 'Week',
      day: 'Day',
      '4day': '4 Days',
    },
    name: null,
    details: null,
    start: null,
    end: null,
    color: '#1976D2', // default event color
    currentlyEditing: null,
    selectedEvent: {},
    selectedElement: null,
    selectedOpen: false,
    events: [],
    dialog: false
  }),
  mounted () {
    this.getEvents()
  },
  puted: {
    title () {
      const { start, end } = this
      if (!start || !end) {
        return ''
      }
      const startMonth = this.monthFormatter(start)
      const endMonth = this.monthFormatter(end)
      const suffixMonth = startMonth === endMonth ? '' : endMonth
      const startYear = start.year
      const endYear = end.year
      const suffixYear = startYear === endYear ? '' : endYear
      const startDay = start.day + this.nth(start.day)
      const endDay = end.day + this.nth(end.day)
      switch (this.type) {
        case 'month':
        return `${startMonth} ${startYear}`
        case 'week':
        case '4day':
        return `${startMonth} ${startDay} ${startYear} - ${suffixMonth} ${endDay} ${suffixYear}`
        case 'day':
        return `${startMonth} ${startDay} ${startYear}`
      }
      return ''
    },
    monthFormatter () {
      return this.$refs.calendar.getFormatter({
        timeZone: 'UTC', month: 'long',
      })
    }
  },
  methods: {
    async getEvents () {
      let snapshot = await dbStore.collection('calEvent').get()
      const events = []
      snapshot.forEach(doc => {
        let appData = doc.data()
        appData.id = doc.id
        events.push(appData)
      })
      this.events = events
    },
    setDialogDate( { date }) {
      this.dialogDate = true
      this.focus = date
    },
    viewDay ({ date }) {
      this.focus = date
      this.type = 'day'
    },
    getEventColor (event) {
      return event.color
    },
    setToday () {
      this.focus = this.today
    },
    prev () {
      this.$refs.calendar.prev()
    },
    next () {
      this.$refs.calendar.next()
    },
    async addEvent () {
      if (this.name && this.start && this.end) {
        await dbStore.collection('calEvent').add({
          name: this.name,
          details: this.details,
          start: this.start,
          end: this.end,
          color: this.color
        })
        this.getEvents()
        this.name = '',
        this.details = '',
        this.start = '',
        this.end = '',
        this.color = ''
      } else {
        alert('You must enter event name, start, and end time')
      }
    },
    editEvent (ev) {
      this.currentlyEditing = ev.id
    },
    async updateEvent (ev) {
      await dbStore.collection('calEvent').doc(this.currentlyEditing).update({
        details: ev.details
      })
      this.selectedOpen = false
      this.currentlyEditing = null
      this.getEvents()
    },
    async deleteEvent (ev) {
      await dbStore.collection('calEvent').doc(ev).delete()
      this.selectedOpen = false
      this.getEvents()
    },
    showEvent ({ nativeEvent, event }) {
      const open = () => {
        this.selectedEvent = event
        this.selectedElement = nativeEvent.target
        setTimeout(() => this.selectedOpen = true, 10)
      }
      if (this.selectedOpen) {
        this.selectedOpen = false
        setTimeout(open, 10)
      } else {
        open()
      }
      nativeEvent.stopPropagation()
    },
    updateRange ({ start, end }) {
      this.start = start
      this.end = end
    },
    nth (d) {
      return d > 3 && d < 21
      ? 'th'
      : ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'][d % 10]
    }
  }
}

Main

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import vuetify from './plugins/vuetify'

// Firebase
import firebase from 'firebase/pat/app';
import 'firebase/pat/firestore';

//I have initialized my project with valid values but mented the keys to avoid publishing them online.
firebase.initializeApp({
  apiKey: "<my_api_key>", 
  authDomain: "<my_project_domain>",
  projectId: "<my_project_id>",
  databaseURL: "",
  storageBucket: "<my_project_storage_bucket>",
  messagingSenderId: "<my_messaging_sender_id>",
  appId: "<my_app_id>",
  measurementId: "<my_measurement_id>"
});

Vue.config.productionTip = false

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


export const dbStore = firebase.firestore();

Share Improve this question edited Sep 23, 2021 at 6:47 pazitos10 1,70916 silver badges25 bronze badges asked Sep 22, 2021 at 16:39 Bjorn RuizBjorn Ruiz 5462 gold badges4 silver badges17 bronze badges 2
  • I can't see you importing dbStore in your script file. Can you share the import statements? – Dharmaraj Commented Sep 22, 2021 at 17:16
  • When you call this.getEvents() it's not guaranteed that dbStore is a hydrated object with the methods you expect. – Ohgodwhy Commented Sep 22, 2021 at 17:53
Add a ment  | 

2 Answers 2

Reset to default 0
  1. Check if you are importing DbStore

  2. Use

    this.dbStore.collection('calEvent').get().then((res)=>{ 
    
        const events = res.docs;
    
    }) 
    

It could be possible that you might not be binding your data correctly, so you need to troubleshoot whether the problem is in the back-end or the front-end. It seems you might not be getting the data correctly before making the structure of the website, you need to get all the data and the database correctly and then you can start construction and binding it to the front-end.

I would first try with mock data, for example, return a json and validate if the app is receiving it or if the network request get a response, if the responses are 200, then validate how is being received to the app with

<pre>{{ yourObject }}</pre>

If it is not empty, then try with real data. If it's also not empty, your data is correctly binded.

You can also hardcode some data in your script to see if the issue is ing from the front-end, like this:

data: () => ({
    today: 14/02/2021
    focus: 14/01/2021
    type: 'month',
  }),

Also you can try using Vuefire to bind your data, this will help you to incorporate Firebase in a better way to VueJS. You can follow this really useful guide on how to bind your data from firestore using Vuefire. To get started, just include Vue, Firebase and VueFire libraries in your page:

<head>
  <!-- Vue -->
  <script src="https://cdn.jsdelivr/vue/latest/vue.js"></script>
  <!-- Firebase -->
  <script src="https://cdn.firebase./js/client/2.4.2/firebase.js"></script>
  <!-- VueFire -->
  <script src="https://cdn.jsdelivr/vuefire/1.0.0/vuefire.min.js"></script>
</head>

VueFire will automatically detect Vue's presence and install itself. If you are using a module bundler, you can also install the dependencies via NPM:

npm install vue firebase vuefire --save

var Vue = require("vue");
var VueFire = require("vuefire");
var Firebase = require("firebase");

// explicit installation is required in a module environment
Vue.use(VueFire);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742343731a4426128.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信