nuxt-community / firebase-module

🔥 Easily integrate Firebase into your Nuxt project. 🔥
https://firebase.nuxtjs.org
MIT License
641 stars 99 forks source link

Nuxt fetch() for Firestore returns empty array #552

Open simeon9696 opened 3 years ago

simeon9696 commented 3 years ago

I'm using the fetch() hook in Nuxt with Firestore and when called on the server it always returns an empty array. If called from the client, it returns a populated array

created(){
  this.$fetch() //  automatically call fetch instead of using a button click. called on client, logs populated array and json
},
async fetch(){
  const products = await this.$fire.firestore.collection('products').get();
  const ps = products.docs.map(doc=>doc.data());
  console.log(ps); //logs an empty array on Nuxt SSR

  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/38`)
  const l = await res.json();
  console.log(l); //always logs a value on client or SSR

} 

Can I have some guidance as to what's happening here and how it solve it? I find it odd that the call to jsonplaceholder always returns data, but the call to firebase does not. See below for an image of console

image

Version

@nuxtjs/firebase: 7.6.1 firebase: 8.6.7 nuxt: 2.15.7

What is Expected?

It should return a populated array

What is actually happening?

Using the fetch() hook in Nuxt with Firestore and when called on the server it always returns an empty array

Beethoven commented 3 years ago

You don't need to call this.$fetch() on Created Fetch hook is called after the component instance is created on the server-side.

https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/

simeon9696 commented 3 years ago

I think I found out why but I've no idea how to fix it. Fetching things on the server is trying to pull it from production and I'm currently using the emulators. My actual production db is completely empty atm.

The screenshot below clued me in on this: image

I added a document to the collection and ran npm run generate and sure enough it pulled the data from the production db. I find it odd because I have a vuex action that (I think) runs server side to add a document to that 'products' collection and that adds it to the emulator.

@lupas @Beethoven any suggestions?

simeon9696 commented 2 years ago

Couldn't figure this out but my workaround is to fetchOnServer only in production:

  async fetch() {
    try {
      const l = await this.$fire.firestore.collection('products').get()
      this.products = l.docs.map((doc) => {
        return { ...doc.data(), id: doc.id }
      })
    } catch (error) {
      console.error(error)
    }
  },
  fetchOnServer: process.env.NODE_ENV !== 'development',