Damac
Damac

Reputation: 119

Nuxt async not work on page reload - firebase

I have a issue with asyncData() when i refresh the page. If I navigate from list to single item, it work, but if i reload the page i will see an empty object. In my page i have this :

<template>
    <div>
        {{ getItem}}
    </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
    data: () => ({
    }),
    computed: {
        ...mapState([
            'single_item'
        ]),
        getItem() {
            return this.single_item
        }
    },

    async asyncData({app,route, params,store}) {
        let type = 'posts'
        let id = params.id
        return store.dispatch('fetchFirebaseSingle', {type,id })
    }
}
</script>

in store.js

    import { db } from '~/plugins/firebase'
    
    const actions = {
    ....
    
    async fetchFirebaseSingle({commit}, {type, id}) {
        try {
          console.log('fetchFirebaseSingle', type)
          const docRef = await db.collection(type).doc(id)
           docRef.get()
          .then((doc) => {
              if (doc.exists) {
                  const file = doc.data()
                  commit('SET_PAGE_SINGLE', file) 
              } else {
                  // doc.data() will be undefined in this case
                  console.log("No such document!");
              }
          })
          .catch((error) => {
            console.log("Error getting document:", error);
          });
    
        } catch (e) {
            console.log("Error getting document:", e);
        }
      },
    }

const mutations = {
...
    // Set Single Item
    SET_PAGE_SINGLE ( state, single_item) {
      state.single_item = single_item
    },
},
const state = () => ({
      single_item : {},
})

I tryed also to call directly from this page the database, but i have same issue. Did someone get similar issue with vuex and firebase or asyncData ? Thanks

Upvotes: 1

Views: 964

Answers (1)

kissu
kissu

Reputation: 46814

Nothing special here, asyncData is not supposed to work on page reload or a refesh (F5) but only with page transitions.

Unlike fetch, the promise returned by the asyncData hook is resolved during route transition

You could use the fetch() hook if you don't mind a non-blocking loading.

More info here: https://nuxtjs.org/docs/features/data-fetching#data-fetching

Upvotes: 2

Related Questions