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

Javascript's callback mechanism allows functions to be passed as arguments

I am currently delving into the intricacies of the callback mechanism in javascript, particularly typescript. If I have a function that expects a callback as an input argument, do I need to explicitly use a return statement to connect it with the actual ca ...

Issues with Mocha's beforeEach() and done() functions not functioning as expected

I am facing an issue with my Mocha test suite. When I run the 'make test' command, I encounter the following error message: Uncaught TypeError: Object [object Object],[object Object] has no method 'done' Below is the relevant code sni ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

The FileReader encountered an error because the first parameter is not a 'Blob' type

I seem to be encountering an issue with a javascript FileReader that is throwing the error Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. This problem occurs intermitt ...

Utilizing dropzone.js in a Vue application to trigger a function with the name of the uploaded image

I'm struggling to make this work as I want to, but I do have a functional dropzone setup in my Vue project. While I can upload images and trigger functions within the dropzone, I'm looking to directly call a function from the HTML form to send t ...

Tips for transferring canvas information from JavaScript to Django using Ajax

Currently, I'm developing a Django application that allows users to activate their webcams and capture photos. These images are stored in a canvas, and my goal is to send this image to Django views so that it can be saved on the server. To trigger th ...

NodeJS sqs-consumer continuously triggers the function to execute

I have been utilizing the npm package called sqs-consumer to monitor messages in a queue. Upon receiving a new message, I aim to generate a subfolder within an S3 bucket. However, I am encountering a problem where even after the message is processed and re ...

Error: Property 'blogCategory' is unreadable because it is undefined

Having trouble rendering blog posts from a json file in React const BlogPost = (props) => { const [post, setPost] = useState({ id: "", blogCategory:"", blogTitle:"", postedOn:"", ...

Launch a YouTube video within a sleek and stylish Bootstrap modal popup

I am currently extracting video data from my SQL table. The fields in the table are as follows: - sidebar_video_id (auto increment) - sidebar_video_nev - sidebar_video_link (full URL) - sidebar_video_v_id (video ID at the end of the URL) What I'm tr ...

Tallying the Number of Accordion Toggle Clicks

Let me present a scenario where I have some accordions and would like to keep track of how many times the user expands each one. Could you guide me on how to implement this particular feature? Appreciate your support, Kevin ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Having difficulty integrating plugins like Lighthouse into my Cypress project

I need assistance with integrating the cypress automation plugin into my project. I made changes to my index.js file in the plugin folder, but now I am receiving this error: cy.lighthouse() is not a function Here is my index.js file content: const { light ...

Creating a unique directive specifically designed to be used within an ng

I have a unique custom directive that I implemented in AngularJS. The directive is called within an ng-repeat loop, as shown below: The array of objects, selectedMealCalc.calculated_foods, is aliased as 'items' <!-- CUSTOM DIRECTIVE --&g ...

Missing ghost image appears when you drag and drop the file

New to JavaScript... As a rookie in coding, I often get interesting requests from my partner who is a kindergarten teacher. Recently, she asked me to create a "Function Machine" for her classroom activities. With some trial and error, I managed to put tog ...

WordPress now features the ability to toggle both parent menu items when clicked, providing a more streamlined user experience

I am currently facing an issue with a menu structure, where parent menu items have submenus that need to toggle on click. However, I am encountering a problem where, upon placing the code inside a forEach loop, both submenus toggle instead of only togglin ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

Retrieve items from the parent row of selected checkboxes

Within my table, I have the following row. <tr class="data_rows" ng-repeat='d in t2'> <td class="tds"> <input class='checkBoxInput' type='checkbox' onchange='keepCount(this)'></td> &l ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...