What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic?

Currently, I am trying to fetch the data on the component's ready hook, but it seems like this function is never being executed:

<template>
    <b-container class="bv-example-row">
        <h1>{{title}}</h1>

        <b-row>
            <b-col>
                {{content}}
            </b-col>
        </b-row>
    </b-container>
</template>

<script>
import api from '../../api'

export default {
    data() {
        return {
            id: '',
            slug: '',
            title: '',
            content: ''
        };
    },

    ready() {
        console.log('foo');
        this.fetchData();
    },

    methods: {
        fetchData() {
            api.getPageBySlug('sample-page', page => {
                this.$set('title', page.title);
                this.$set('content', page.content);
            });
        }
    }
};
</script>

Answer №1

Vue.js 2 does not have a ready() hook available.

If you need to include Ajax code, you can place it in various lifecycle hooks. The commonly used ones are listed in the lifecycle hooks documentation:

  • beforeCreate()
  • created()
  • beforeMount()
  • mounted().

There are certain considerations that should guide your decision on which hook to use.

First: Vue's initialization code runs synchronously.

This means that any asynchronous code executed in these hooks will only complete after all the initial hooks have finished. For example, if you make an Ajax call in the beforeCreate hook, the response will be processed after the created() hook has been executed.


Determining the Suitable Hook to Use

  • Need to trigger a call as soon as possible?
    • Use beforeCreate()
    • Why?
      • This hook runs before any other hooks, allowing for immediate execution of code.
  • Need to read from or modify data right away?
  • Require functionality generated post-created()?
    • Use beforeMount()
    • Why?
      • There are rare cases where additional features become accessible at beforeMount(). One such instance is the compiled render function this.$options.render.
  • Need access to DOM elements (e.g., ref)?
    • Utilize mounted()
    • Why? These are only available once the component has been mounted.

Using Vuex for Global State Management

If you are leveraging Vuex to maintain global state, initiate requests within Vuex actions. From there, components can dispatch actions as needed in any lifecycle hook or method. Refer to the demonstration below for illustration.

// Vuex store setup
const store = new Vuex.Store({
strict: true,
  state: {
    people: []
  },
  mutations: {
    populate: function (state, newPeople) {
      state.people = newPeople
    }
  },
  actions: {
    fetchPeople ({ commit }) {
      axios.get('https://reqres.in/api/users').then(function (response) {
        commit('populate', response.data.data)
      }, function () {
        console.log('error')
      })
    }
  }
});

// Vue Component
Vue.component('mycomp', {
  computed: Vuex.mapState(['people']),
  template: `
    <ul>
      <li v-for="p in people">
      {{ p.first_name }} {{ p.last_name }}
      </li>
    </ul>
  `
});

new Vue({
  // Link to Vuex store
  store,
  el: '#app',
  created() {
    this.$store.dispatch('fetchPeople'); // Dispatch Vuex action
  },
  computed: Vuex.mapState(['people']),
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  In parent:
  <ul>
    <li v-for="p in people">
      {{ p.first_name }} {{ p.last_name }}
    </li>
  </ul>
  <hr>
  In custom component (data fetched once):
  <mycomp></mycomp>
</div>

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

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Display the Bootstrap datepicker within an h4 element set to default to today's date, utilizing both Angular and jQuery

Utilizing Boostrap datepicker to obtain the selected date from the calendar and insert it into an <h4> html tag. However, my goal is to display today's date by default in the h4 when it opens for the first time. Using angular.js + jquery f ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

Ways to retrieve the data from promises after they have been resolved?

I'm struggling to retrieve the values from getPeople(0,4). function getPeople(start, end) { const peopleArray = []; for (let i = start; i <= end; i++) { peopleArray.push( axios.get(`https://www.testsite.net/api/test/workers/ ...

What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

I am attempting to send a message via a web socket to the server when a button is clicked: // HelloApp.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button v-on:click="sendMessage($event)">Send Message< ...

Updating $data within a VueJS directiveIs there something else you

We have a component and a directive. The structure of our component data is as follows: { langs: [ { title: '', content: '' }, { title: '', content: ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Emulate the selection process using element-ui and vue-test-utils

During my unit tests using Jest and Element-ui in Vue, I encountered an issue with a component containing a select element with 2 options. After selecting an option from the dropdown, I needed to verify that a specific action was called. 1) Everything wor ...

Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually. The code I am using utilize ...

Guidelines on centering an AJAX spinning animation within a parent div

Below is the basic structure of an HTML document for a webpage. <div class="grand-parent"> <div class="header">Heading</div> <div class="parent-div"> <div class="child-div-1"></div> ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

The art of transforming properties into boolean values (in-depth)

I need to convert all types to either boolean or object type CastDeep<T, K = boolean> = { [P in keyof T]: K extends K[] ? K[] : T[P] extends ReadonlyArray<K> ? ReadonlyArray<CastDeep<K>> : CastDeep<T[P]> ...

It is essential for Jquery to properly evaluate the first JSON result, as skipping

I'm currently facing an issue where the first JSON result is being skipped when I try to evaluate a set of JSON results. Below is the Jquery code snippet in question: function check_product_cash_discount(total_id){ //check for cash discount ...

What is the best way to create a JSON string using JavaScript/jquery?

Is there a way to programmatically build a JSON string? The desired outcome should resemble the following: var myParamsJson = {first_name: "Bob", last_name: "Smith" }; Instead of constructing the entire object at once, I would prefer adding parameters one ...

Resolve character encoding issues in a JavaScript CSV HTTP response file

When I receive a CSV file as a response from an API, I encounter issues with special characters in French appearing distorted. The content in the CSV files looks like this: Exampleé of Weiéérdnesséé Is there a way to standardize these ...

Comparing Weex components: <list> versus <recycle-list>

Currently, I am working on a Weex application using Vue.js. My main focus is on creating a list component and while going through the documentation, I came across two components that caught my attention: <list> <recycle-list> I'm curio ...

Methods for concealing a single item in a Vue web form

I am a beginner with Vue and I am facing a challenge in hiding a specific element within a web form that is part of a loop. I am trying to use v-if along with a showHideEditComponent method call. However, when I invoke the showHideEditComponent method wi ...