Displaying a component following data retrieval in Vue.js

I am currently working on consuming an API using axios.

Here is the code I have so far:

<select>
    <option v-for="value in values"> value.name </option>
</select>

   // js
   data(){
        values: [],
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.value = res.data.dados;
              console.log(res.data.dados);
          })
          .catch(error => {
               console.log(error);
          });
   }
}

The console.log inside the promise is displaying results, but the options with data are not rendering. It seems like my select component is being rendered before 'getData()' is called. How can I resolve this issue?

Answer №1

Make sure to include a loading handler in your code.

<select v-if="loaded">
  <option v-for="value in values"> value.name </option>
</select>

   // JavaScript
   data(){
        values: [],
        loaded: false,
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.value = res.data.dados;
              this.loaded = true;
          })
          .catch(error => {
               console.log(error);
               this.loaded = true;
          });
   }
}

Answer №2

There seems to be a mistake in your code involving this.value, it should actually be this.values. If that correction doesn't work, try using this.$forceUpdate() to forcefully re-render the component

<select>
    <option v-for="value in values">{{ value.name }}</option>
</select>

   // js
   data(){
        values: [],
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.values = res.data.dados; // change value to values
              console.log(res.data.dados);
              this.$forceUpdate(); // add forceUpdate
          })
          .catch(error => {
               console.log(error);
          });
   }
}

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

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

Delaying the activation of the code until the image upload is complete

I'm having trouble synchronizing code to upload an image using a vue composable, wait for the upload to finish, and then store the Firebase storage URL into a database. Despite getting the URL, the success code fires before the upload is complete. My ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

Combining functions in React is a powerful way to create

Is there a way to create a single function that combines handleSelectAll and handleSelectNone for toggling options in a list of categories? Instead of using a toggle (on/off) approach, I believe having separate buttons for Select All and Select None is mor ...

Tips for Setting up SQLite Database Connection in VueNative App

Struggling to establish a connection to SQLite database in vueNative. Unsure of the steps to take. Could someone lend a hand? Seeking guidance on how to connect to SQLite db within a vueNative app. ...

Attempting to retrieve backend data through an API to be displayed on the frontend

After successfully sending form data from my React front end to the server using fetch, I am struggling to make this data accessible from the front end again. Despite being able to access and utilize the data within my API function on the server side, I&ap ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

What is the best way to trigger a function in Vue when leaving a specific route?

I'm in the process of finding a way to clear local storage when the user navigates away from the current page. How can I achieve this? I attempted to use the destroyed() lifecycle hook but it didn't work as expected. Would utilizing beforeRouteLe ...

The Angular directive is failing to refresh the data on the Google Map

I created a directive called "myMap" to incorporate a Google map into my application. However, I am facing an issue when attempting to update the longitude and latitude values for a different location using a controller function. The directive does not ref ...

What is the limitation in transmitting data as a JavaScript object rather than a JSON object?

As a newcomer to expressjs, I recently developed an application using it. Interestingly, when I send data in JSON format through POSTMAN, the application successfully returns the data. However, when I try to send data as a JavaScript object in the request ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

What is the process of refreshing a page post-loading?

I'm working on a fundraising webpage and I want to display the live amount of money raised. Essentially, when one user donates while another is viewing the total amount raised, I want the displayed number to update in real-time. My backend setup incl ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

I encountered an error while trying to add a document to Firestore using the 'add' method in Vue.js. Can someone provide guidance on how to

Whenever the function is triggered (on click), I aim to include a new document. Although it functions with .set(), my goal is for a new document to be created each time the form is submitted. The current error code I am encountering is: I initially suspe ...

Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach: angular.module('myapp',[]),directive('mydirective', function() { var directive = {}; directive.restrict = 'E'; directi ...

Iterate through the array to verify that the specified conditions are satisfied for each individual item

I am working with an array of items and need to check if they all meet specific criteria. I've created a for loop to iterate through the array, but I'm concerned about its efficiency. Is there a more optimal way to achieve this? let match = 0; ...

Encountered an import error when using "npm run build", but it runs successfully with "npm start"

My React app is running smoothly with npm start, but I encounter an error when trying to build it using npm run build. The error message I receive is: `Creating an optimized production build... Failed to compile. Attempted import error: './parseq-lan ...

Passing the app variable from Express.js to routes

I am attempting to transfer some data from the app (variable defined as var app = express();) to some Socket.IO related code by sending a value to a middleware in a similar manner: function routes(app) { app.post('/evento', function (req, re ...