Data is not loaded until after the HTML for the Nuxt page has been

My issue is that I have a dynamic page where product details are loaded, but the html code loads before the data. This results in errors when trying to use static elements like images because the "product" object does not exist.

To address this problem, I added v-if="product != undefined" to every dynamic element, which solves the issue but doesn't seem like an optimal solution.

The data is fetched from the store in the following way:

Within my page component:

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

In the 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 attempted to replace mounted() with: beforeMount(), created(), fetch() but none of them resolved the issue.

I also tried:

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

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

Answer №1

If you want to trigger the dispatch of fetchProducts, you can utilize the fetch hook:

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

To ensure that the data isn't rendered until it's ready, you can use the $fetchState.pending flag in your template:

<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>

Check out this demo for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with the execution of Javascript code. Edit required

After creating a registration form that allows users to input their information for registration, I encountered an issue where if certain fields were left empty or if the user name was unavailable or the email address was already registered, a warning mess ...

Can csrf protection effectively secure data being posted to a server via axios?

In my current project, I am utilizing Laravel but it is not a Vue Single Page Application (SPA) so no routes are being used. Instead, the registration, login, and other form interactions are done through modals using Vue. Axios is being used to send form ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Having trouble sending data to an API through jQuery: the function is not functioning properly

Currently, I am in the process of developing an HTML form that allows users to input values into text fields and submit them to an external API called ThingSpeak. This API then uses the received values to generate a plot displayed within an iframe. Althoug ...

Unfortunately, we encountered an AJAX error while trying to access data from the website datatables.net. You can find

I'm currently working on adding data to a datatables.net datatable using a JSON response, following the example provided here. To achieve this, I am making use of an AJAX call to fetch a JSON response from a database. After obtaining the data, I uti ...

What are the best practices for utilizing the "this" keyword with fetch?

After extensively studying ES6 documentation and the changes it brings, I am eager to incorporate the new oop syntax along with modern libraries such as fetch. Below is the code snippet I have been working on: apiCall(url, thisAlias=this){ fetch(url). ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

Ways to resolve the issue: The property 'X' is not recognized on the '{ object }' data type

Just getting started with vuejs and encountering an error in my vue file Issue: Property 'ClientsSrv' is not recognized on type '{ name: string; props: {}; data(): { ClientsSrv: ClientsService | null; ClientsList: ClientsModel[] | null; IsR ...

Tips for dynamically updating values when input numbers are modified using JavaScript

Check out this amazing tip calculator on netlify. I successfully built it using html, scss, and javascript without relying on any tutorials. Despite taking longer than expected due to being a beginner, I am proud of the outcome. Now, I need some assistanc ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Alter the class when $dirty occurs in Angular

I've recently started working with angular js and am attempting to incorporate animations into my login page. I have created a controller that will modify the class of the input field when clicked and when blurred. app.controller("con", function($sc ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

What benefits does React offer that jQuery does not already provide?

What sets ReactJS apart from jQuery? If jQuery can already handle everything, why should we use React? I've tried to research on Google but still don't have a clear answer. Most explanations focus on terms like "views," "components," and "state" ...

A VueJs component experiencing difficulty retrieving data from its parent instance

I recently started learning VueJS and I'm having trouble with a simple example from the documentation. Here is the code snippet that I expected to display "Howdie Partners" on the page: HTML <div id="app"> <greeting></greeting> ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...

What is the reason behind my button appearing beneath my links in React?

Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu includes a div that wraps a Butt ...

What strategies can be utilized to manage a sizable data set?

I'm currently tasked with downloading a large dataset from my company's database and analyzing it in Excel. To streamline this process, I am looking to automate it using ExcelOnline. I found a helpful guide at this link provided by Microsoft Powe ...

Check for compatibility of overflow:scroll with mobile browsers

Is there an easy JavaScript method that works across different devices and libraries? I am looking to assign a class to the html element in order to enable scrollable containers on mobile devices when needed. I want to follow a similar approach to Modern ...