NuxtN
Nuxt14mo ago
8 replies
suhaylmv

Weird firebase error

Expected first argument to collection() to be a CollectionReference, a DocumentReference or Firebase


plugins/firebase.client.js
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore"

export default defineNuxtPlugin(() => {
  const firebaseConfig = {
  // api keys...

// Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);

  const db = getFirestore(app)

  return {
    provide: {
      firebaseApp: app,
      db,
    }
  }
})


stores/posts.ts
import {defineStore} from 'pinia'
import {addDoc, collection, getDocs} from 'firebase/firestore'
import { v4 as uuidv4 } from 'uuid';

export const usePostStore = defineStore('postStore', {
  state: () => ({
    posts: [],
  }),
  actions: {
    async fetchPosts(){
      const {$db} = useNuxtApp()

      const snapshot = await getDocs(collection($db, 'posts'))
      this.posts = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data()}))
    },

    async addPost(postData){
      const {$db} = useNuxtApp()

      let id = uuidv4()
      const post = {
        hash_id: id,
        creationDate: "21-11-2024",
        title: postData.title,
        location: postData.location,
        schedule: postData.schedule,
        shift: postData.shift,
        description: postData.description
      }

      try {
        const docRef = await addDoc(collection($db, "posts"), post);
        this.posts.push({ id: docRef.id, ...post });
      } catch (error) {
        console.error("Error adding post:", error);
      }
      console.log($db);
    }
  }
})
image.png
Was this page helpful?