How can I ensure that VueJS only starts loading data after the initial API call has been completed?

After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent the Update button from being enabled if any value has changed after the initial data population.

<template>
  <div id="app">
    <input type="text" v-model="user.userId" /> <br />
    <br />
    <input type="text" v-model="user.title" /> <br />
    <br />
    <button :disabled="isDisabled">Update</button>
  </div>
</template>

<script>
export default {
  name: "App",
  watch: {
    user: {
      handler(oldVal, newVal) {
        if (oldVal != newVal) {
          this.isLoaded = false;
        }
      },
      deep: true,
    },
  },
  computed: {
    isDisabled() {
      return this.isLoaded;
    },
  },
  async created() {
    await fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        this.user = json;
        this.isLoaded = true;
      });
  },
  data() {
    return {
      user: {
        userId: 0,
        id: 0,
        title: "",
        completed: false,
      },
      isLoaded: true,
    };
  },
};
</script>

I have looked into resources like Vue, await for Watch, Are watches asynchronous?, and Vue.js How to watcher before mounted(), can't get data from watch, but I am struggling to implement their suggestions.

See the live example here: https://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark

Answer №1

In order to arrive at a solution, certain conditions must be taken into consideration.

Although isLoaded currently determines the state of initial loading, its name can cause confusion as it actually signifies that data is not loaded.

A more appropriate approach could be:

  watch: {
    user: {
      if (this.isLoading && oldVal != newVal) {
        this.isLoading = false;
      }
      ...

The watcher may not require being deep and can be removed when no longer necessary:

async created() {
  let unwatchUser = this.$watch('user', (oldVal, newVal) => {
    if (this.isLoading && oldVal != newVal) {
      this.isLoading = false;
      unwatchUser();
    }
  })
  ...

An alternative way to indicate that data has not been loaded yet is by setting it to null, representing no value. This eliminates the need for an isLoading flag or a watcher. If null is unsuitable due to referred object properties, optional chaining and conditional rendering can be utilized:

  <div v-if="user">
      <input type="text" v-model="user.userId" />
      ...
  <div v-else class="spinner"/>

Answer №2

Here is a straightforward solution to the problem:

Q: How can I wait for the initial API data load in VueJS before displaying?

A: You can add a flag inside your watch (e.g. isLoaded).

Additionally, there are a few issues with your code:

  • Using async/await in created does not serve any purpose,
  • The isDisabled variable is unnecessary since it depends on only one value from data. You can directly use this value (isLoading) instead.
  • If your API calls fail, the isLoading flag will not change. A better approach would be to move it to the `finally` block.

For the solution to your specific issue, you can refer to this codesandbox:

<template>
  <div id="app">
    <div v-if="!isFetching">
      <input type="text" v-model="user.userId" /> <br />
      <br />
      <input type="text" v-model="user.title" /> <br />
      <br />
      <button :disabled="!isLoaded">Update</button>
    </div>
    <div v-else>Loading...</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      user: {
        userId: 0,
        id: 0,
        title: "",
        completed: false,
      },
      isFetching: false,
      isLoaded: false
    };
  },
  watch: {
    user: {
      handler(oldVal, newVal) {
        if (!this.isFetching) {
          // The comparision here doesn't work as oldVal/newVal are objects
          if (oldVal != newVal) {
            this.isLoaded = false;
          }
        }
      },
      deep: true
    },
  },
  created() {
    this.isFetching = true;
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        this.user = json;
        this.isLoaded = true;
      })
      .finally(() => this.isFetching = false)
  },
};
</script>

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

Creating a shared singleton instance in Typescript that can be accessed by multiple modules

Within my typescript application, there is a Database class set up as a singleton to ensure only one instance exists: export default class Database { private static instance: Database; //Actual class logic removed public static getInstance() ...

Layer one image on top of another using z-index

I'm having trouble layering one image on top of another in my code. Here is my code: body { background: #000000 50% 50%; height: 100% width:100%; overflow-x: hidden; overflow-y: hidden; } .neer { z-index: 100; position: absolute; } ...

Using jQuery to retrieve the text content of child elements

Struggling to extract the text of child elements using jQuery. I've been at this for a couple of days and can't seem to make it work. If anyone could spare a moment to review, I would greatly appreciate it! SCRIPT: function generateRemoveSect ...

Uninterrupted text streaming with dynamic content that seamlessly transitions without any gaps

I'm currently facing a challenge with an outdated element like <marquee>. Here's a fiddle where you can check it out: https://jsfiddle.net/qbqz0kay/1/ This is just one of the many attempts I've made, and I'm struggling with two m ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

Controlling user login sessions and cookies with angular.js is essential for ensuring secure and seamless

I have a login application where I need to implement session and cookies using angular.js. Below is the code for my login functionality. loginController.js: var loginAdmin=angular.module('Channabasavashwara'); loginAdmin.controller('log ...

What is the method for retrieving the name of the currently selected HTML element?

After using jQuery to select certain tags, I am now trying to obtain the name of each tag: $('select, :checkbox, :radio').each(function(){ // ... }); To accomplish this, I have attempted the following code: $('select, :checkbox, :radio ...

What is the reason for Javascript XMLHttpRequest returning the octet-stream MIME type response as a string instead of binary

My attempt to retrieve a gltf binary file using the XMLHttpRequest method was unsuccessful. Below is the code I used. var xhr = new XMLHttpRequest(); xhr.open("GET","THE ADDRESS",true); xhr.setRequestHeader("Accept", "application/octet-stream"); xhr.respo ...

Generating a JavaScript array using concealed data

var a1=$("#orderprogress").val().toFixed(2);//a1=50 var a2=$("#poprogress").val().toFixed(2); //a2=70 If I were to create an array in this format, how should I proceed? graphData = new Array( [a1 value,'#222222'],//[50,'#22222 ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

Encountering an "Undefined index" error when attempting to send a file and path using FormData through

I have a question about my code. I am trying to send a file and a path to the server. The path needs to be constructed using these variables so that I can use it to output the file later on. var FD = new FormData(); var MyString = "uploads/docs/KEP" + m ...

Fetch information that was transmitted through an ajax post submission

How can I retrieve JSON formatted data sent using an ajax post request if the keys and number of objects are unknown when using $_POST["name"];? I am currently working on a website that functions as a simple online store where customers can choose items m ...

The dot operator cannot be used to access Json objects

Utilizing a4j jsFunction to transmit data to the server and receive JSON in return <a4j:jsFunction name="submitData" action="#{imageRetriveBean.saveData}" data="#{responseNodesPathsBean}" oncomplete="processData(event.data)"> <a4j:param name= ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...