VueJS: Preloading data prior to and following component initialization

VueJS is a new technology for me, and I'm currently working on a component that needs to retrieve data from an API before loading the corresponding route. The component should only load once the data is fetched. Additionally, after the component is created, I need to call another API that uses the data obtained from the first API as input. Below is the script for my component:

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  created () {
     // it gives length = 0 but it should have been categories.length
      console.log(this.categories.length);

    // Call getImage method
    loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {}
}

I attempted to use the mounted hook, but it didn't work as expected. However, when I used a watch on the categories property and called the fetch image method, it worked. I'm unsure if using watchers is the best approach in this scenario. Any suggestions?

Answer №1

Organize your code by moving the call for additional information into a separate method and then invoking that method from the next function.

export default {
  name: 'login',
  data () {
    return {
      categories: []
    }
  },
  beforeRouteEnter (to, from, next) {
    loginService.getCategories().then((res) => {
      next(vm => {
        vm.categories = res.data.categories;
        vm.getMoreStuff()
      });
    }, (error) => {
      console.log('Error: ', error);
      next(error);
    })
  },
  methods: {
    getMoreStuff(){
      console.log(this.categories.length);

      // Call getImage method
      loginService.getImage(this.categories.length)
        .then(res => {
            console.log('Images fetched');
        })
    }
  }
}

Another approach could be to handle it within the callback for getCategories.

loginService.getCategories()
  .then(res => {
    vm.categories = res.data.categories;
    loginService.getImage(vm.categories.length)
      .then(res => //handle images then call next())
  })
  .catch(err => //handle err)

Alternatively, if you are using a pre-compiler that supports async/await functionality

async beforeRouteEnter(to, from, next){
  try{
    const categoryResponse = await loginService.getCategories()
    const categories = categoryResponse.data.categories
    const imageResponse= await loginService.getImage(categories.length)
    next(vm => {
      vm.categories = categories 
      vm.images = imageResponse.data.images
    })

  } catch(err){
    //handle err
  }
}

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 there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

The order of key:value pairs in documents created by Mongoose does not always align with the schema

Having trouble understanding how the Mongo .create and .findAndUpdate operations work. My mongoose version is 5.4.2X and I have a model with a schema containing multiple key:value pairs in a specific order (using 1. 2. 3. etc to indicate the correct order) ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

Selecting the appropriate v-model for Vue.js draggable in the case of a nested list

My Vue Component <div id="main"> <h1>Vue Dragable For</h1> <div class="drag"> <ul> <li v-for="category in data"> <draggable id="category" v-model="category" :move="checkMo ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

Has the Soundcloud web widget API become obsolete?

I am currently working with the SoundCloud widget API (). My main goal is to retrieve information about the tracks within a set. Unfortunately, it seems like I am only able to utilize the methods widget.getSounds() and widget.getCurrentSound successfully ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

When utilizing TinyMCE in numerous Vuetify dialogs, the editor appears completely empty

My challenge is using TinyMCE in multiple dialogs, as switching dialogs causes the TinyMCE editor to become blank and uneditable. To showcase the issue I'm facing, I have prepared a demo accessible here: https://codesandbox.io/s/tinymce-vue-demo-fork ...

Vue.js Class-based Decorator not Transmitting Event from Child to Parent Component

I'm fairly new to working with Vue.js and I've encountered an issue with the child to parent emit functionality. Essentially, I have a Box component that contains a Search component. In the Search component, I attempted the following: @Watch("se ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

Issue with $watch in Angular Modal not triggering

Having trouble using $watch with a radio button located inside an AngularJS Modal. The $watch doesn't seem to work when the value changes within the modal. If I move the radio buttons outside the modal, the $watch functions as expected. You can see ...

JavaScript validation for radio buttons that are grouped together

Need help with a JavaScript validation issue regarding grouped radio buttons named optionRadios1 to 5. I'm trying to validate them before submitting the form, but my code isn't working as expected and still allows the form submission. Below is t ...

Is it possible to capture and handle browser-specific errors that occur during an AJAX call? I am having trouble locating and capturing these errors

My goal is to thoroughly test an AJAX call for potential errors by deliberately breaking it in various ways. The error callback in jQuery ajax does not provide detailed information like what the browser logs, which is what I need to capture. For example, C ...

Execute a single test from a particular test suite using Jest

Within my file named "test-file-1", I have several describes (test suites) with distinct names, each containing tests that may share similar names across different test suites. In order to run a single test suite or test, I enter the following command: n ...

Conceal object after a brief pause

Why does the element hide immediately instead of slowly fading out? I can't figure out why it doesn't first display the "P" tag and then gradually hide it. Please help me solve this issue. var step = 0.1; var delay = 90000; var displayMe = fun ...

Can anyone explain how to successfully implement AJAX data in a PHP file?

I've been struggling to transfer data from my JavaScript file to a PHP variable. I've spent hours searching for solutions, but none seem to apply to my unique code. Here's the JavaScript code I'm working with... $(function(){ ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

The WHATWG URL API allows creation of a new URL using the new URL

I've been experimenting with node and attempting to create an instance of the URL class to utilize its useful properties. Here's what I tried: const { URL } = require('url'); (...) http.createServer((request,response) => { let u ...

Guide to activating the isActive status on a live link within a map iteration utilizing the NEXTUI navigation bar

Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...