Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading