The fetch feature is only activated upon refreshing the page

Attempting to utilize the new Nuxt.js Fetch method has presented an issue. Initially, everything seemed to be working properly. However, I noticed that the data is only fetched and displayed upon refreshing the page. When accessing the page through $fetchState.error being true, the data fails to fetch altogether.

I am unsure of what mistake I might have made in this scenario.

<template>
  <main>
    <div>
      <div>
        <p v-if="$fetchState.pending">
          Fetching vehicles...
        </p>
        <p v-else-if="$fetchState.error">
          Error while fetching vehicles
        </p>
        <div
          v-for="(vehicle, index) in usedVehicles"
          v-else
          :key="index"
        >
          <nuxt-link :to="`cars/${vehicle.Id}`">
            {{ vehicle.Make }}
          </nuxt-link>
        </div>
      </div>
      <button @click="$fetch">Refresh Data</button>
    </div>
  </main>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      usedVehicles: []
    }
  },
  async fetch() {
    const { data } = await axios.get(
      'https://random.com/api'
    )
    // `todos` has to be declared in data()
    this.usedVehicles = data.Vehicles
  },
  methods: {
    refresh() {
      this.$fetch()
    }
  }
}
</script>


Answer №1

Recently addressed a similar query about fetch

In the life cycle hooks,

The fetch is invoked (but only completes after the page has been mounted). This implies that when you refresh the page, the data should be stored in the client's cache (thus rendering this.usedVehicles).

If you want to ensure that the data is fetched before the initial mount, you can utilize asyncData and await the call - ensuring that usedVehicles is assigned prior to the page being mounted.

Here's an example:

<template>
  <main>
    <div>
      <div>
        <p v-if="$fetchState.pending">
          Fetching vehicles...
        </p>
        <p v-else-if="$fetchState.error">
          Error while fetching vehicles
        </p>
        <div
          v-for="(vehicle, index) in usedVehicles"
          v-else
          :key="index"
        >
          <nuxt-link :to="`cars/${vehicle.Id}`">
            {{ vehicle.Make }}
          </nuxt-link>
        </div>
      </div>
      <button @click="$fetch">Refresh Data</button>
    </div>
  </main>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      usedVehicles: []
    }
  },
  async asyncData() {
    const { data } = await axios.get(
      'https://random.com/api'
    )

    return { usedVehicles: data.Vehicles }
  }
  async fetch() {
    const { data } = await axios.get(
      'https://random.com/api'
    )
    // `todos` has to be declared in data()
    this.usedVehicles = data.Vehicles
  },
  methods: {
    refresh() {
      this.$fetch()
    }
  }
}
</script>

This approach implies that there will be some delay in fetching the data on each request - but this may align with your intended outcome.

https://i.sstatic.net/sKpVI.png

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

Is it possible to stop the manipulation of HTML and CSS elements on a webpage using tools similar to Firebug?

How can we prevent unauthorized editing of HTML and CSS content on a webpage using tools like Firebug? I have noticed that some users are altering values in hidden fields and manipulating content within div or span tags to their advantage. They seem to be ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

What is the procedure to incorporate login credentials into the source of an iframe?

Is there a way to pass user auto login in the src URL? <iframe src="https://secure.aws.XXX.com/app/share/28228b0ccf0a987" width="1060px" height="1100px"></iframe> I attempted to achieve this, but it still shows the login screen <ifr ...

Troubleshooting the problem of fast rotation and scrolling of text in the middle but slow movement at the end with

Currently, I am utilizing the jquery animate function for animating text while also aiming to rotate the text if a specific degree is passed. In order to achieve this, I have implemented the following code snippet: var leftCss = "-"+$('#mydiv'). ...

Emulate mobile view using Javascript and HTML simulation tool

I am trying to simulate the appearance of a website on a mobile phone. For example, consider the following code: <div> <div class = "col-md-6 col-sm-6 col-xs-12"> First </div> <div class = "col-md-6 col-sm-6 col-xs- ...

Vue's beforeRouteEnter hook patiently awaits for the child component to complete its request

My Vue app utilizes beforeRouteEnter to load data and prevent the undesirable "flash of unloaded content." Loading data on some pages is straightforward: async beforeRouteEnter(to, from, next) { const newestPosts = await getNewestPosts(); next(vm ...

What is the best way to populate all data in select2 (4.0) upon page load?

I'm currently utilizing the select2 plugin (v.4.0) and have a specific goal in mind: $("#search-input-chains").select2({ placeholder: "Unit", theme: "bootstrap4", ...

What is the minimum number of characters required to embed JavaScript using the HTML5 <script> element?

Is this the most efficient way to include external JavaScript on a page, now that the type attribute of the <script> tag can be omitted in HTML5? <script src="URL"></script> Is there a way to optimize this further, especially if a frame ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Is it possible to automatically direct an iframe video to another video once it finishes

I'm having some trouble adding a video to my website. I want the video to redirect to another page on my site once it finishes playing. I've searched through various forums, but none of the solutions seem to work for my specific situation. Below ...

Tips for updating ng-repeat when the modal is closed?

Scenario: I've got a page (angular) containing a repeater. <tr ng-repeat="row in results.leads"> <td>{{row.SubmittedByName}}</td> Inside the repeater, there's a button in a column that triggers a modal to modify the data o ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

Manipulating content with JavaScript in Internet Explorer using the outerHTML property is a powerful

Encountering an Issue with outerHTML in IE Browser If I try the following: txt = "Update Complete!"; msg = sub.appendChild(d.createElement("p")); msg.outerHTML = txt; It works without any problem. However, if I use: txt = "1 Error:<ul><li> ...

Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected. Here's what I have: Javascript: global.calculateWithCb = function(temp,cb){ cb(5 * temp) } global.calculate = functi ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Identify the geometric figure sketched on the canvas using the coordinates stored in an array

After capturing the startX, startY, endX, and endY mouse coordinates, I use them to draw three shapes (a line, ellipse, and rectangle) on a canvas. I then store these coordinates in an array for each shape drawn and redraw them on a cleared canvas. The cha ...

What is the method to load iframes individually?

Trying to figure out a way to load 6 iframes on page A.php, each containing content from sub pages a1.php~a6.php. The catch is that before loading each sub page, an AJAX call needs to be made to update the database. Additionally, these sub pages must be lo ...