Search code examples
javascriptvue.jsnuxt.jspugstore

Nuxt page HTML is loaded before data


I have a dynamic page that loads product details, but the html is loaded before the data.

So when I try to use static elements like an image I get an error stating the object "product" does not exist.

To fix this I gave every dynamic element v-if="product != undefined" which does work, but doesn't seem like a very good way of solving this.

I'm initiating my data through the store like this

In my page i do:

async mounted() {
  await this.fetchProducts()
},
computed: {
  product() {
    return this.$store.state.products.producten.filter(product => product.id == this.$route.params.id)[0]
  }
}

Then in my store:

export const state = () => ({
  producten: []
})

export const mutations = {
  setProducts(state, data) {
    state.producten = data
  }
}

export const actions = {
  async fetchProducts({ commit }) {
    await axios.get('/api/products')
      .then(res => {
        var data = res.data
        commit('setProducts', data)
      })
      .catch(err => console.log(err));
  }
}

I tried replacing mounted() with: beforeMount(), created(), fetch() but none seemed to work.

I also tried:

fetch() {return this.$store.dispatch('fetchProducts')}

Loader(v-if="$fetchState.pending")
Error(v-if="$fetchState.pending")
.product(v-else)
  // Product details...


Solution

  • You could use the fetch hook to dispatch fetchProducts:

    <script>
    export default {
      fetch() {
        return this.$store.dispatch('fetchProducts')
      }
    }
    </script>
    

    In your template, use the $fetchState.pending flag to prevent rendering the data elements until ready:

    <template>
      <div>
        <Loader v-if="$fetchState.pending" />
        <Error v-else-if="$fetchState.error" />
        <Product v-else v-for="product in products" v-bind="product" />
      </div>
    </template>
    

    demo