Tips for implementing a settimeout function in a VUEJS script

I'm currently working on my first Vue.js application and I'm facing an issue with the initial data upload in the script. After modifying the data received from a database call, I encounter an error during the page's initial load which resolves itself after a few seconds. I attempted to use setTimeout to delay the function execution but it resulted in an error within the Vue.js framework. How can I correctly implement this setTimeout?

Below is a snippet of my script:


<script>
  export default {
    data () {
      return {
        step: 1,
        selected: 1
      }
    },
    components: {

    },
    computed:{
      selectedBasket() {        
        return !this.$store.getters.basket ? null : this.$store.getters.basket
      },
      items(){
        return !this.$store.getters.items ? null : this.$store.getters.items
      },
      filteredEstimation(){
        this.$store.getters.estimations.map(function(estimation) {
          estimation.offers.map(function(offer) {
            offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
            if (offer.name.includes("first")) {
              offer.description = "first option";
            }
            if (offer.name.includes("second")) {
              offer.description = "second option";
            }
            if (offer.name.includes("third")) {
              offer.description = "third option";
            }
          });
        });
        return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
      }, 
      setTimeout(() => {}, 700); // This line should be revised
    },
    methods: {
      getItemsName(item) {

        if(item === 1){
          return 'bag';
        } else if(item === 2){
          return 'paper';
        } else {
          return 'pen';
        }
      }
     }
   };
</script>

Answer №1

It is not recommended to use that function inside the computed option, you should define it in the mounted hook as shown below:


<script>
  export default {
    data () {
      return {
        step: 1,
        selected: 1
      }
    },
    components: {

    },
    computed:{
      selectedBasket() {
        
        return !this.$store.getters.basket ? null : this.$store.getters.basket
      },
      items(){
        return !this.$store.getters.items ? null : this.$store.getters.items
      },
    },
    methods: {
      getItemsName(item) {

        if(item == 1){
          return 'bag'
        } else if(item == 2){
          return 'paper'
        } else {
          return 'pen'
        }
      }
    },
    mounted(){

      setTimeout(() => {
       filteredEstimation(){
        this.$store.getters.estimations.map(function(estimation) {
          estimation.offers.map(function(offer) {
            offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
            if (offer.name.includes("first")) {
              offer.description = "first option";
            }
            if (offer.name.includes("second")) {
              offer.description = "second option";
            }
            if (offer.name.includes("third")) {
              offer.description = "third option";
            }
          });
        });
        return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
      }, 700);

  }
  }
</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

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

a guide on using ajax to distribute retrieved data among various td elements

After the user presses a button, the data is saved into the database. Upon success, I need to retrieve the data from the database and place it in the appropriate td (in the same row as the clicked td). I've been able to successfully retrieve the data, ...

I'm looking to search through multiple indices in Algolia using different search parameters for each index. How can I achieve this with Vue Instantsearch?

I've been using Vue Instantsearch and dealing with multiple indices. Within the ais-search-box component, I have set up a query to search through two indices simultaneously and display the results using an ais-autocomplete component. Everything is w ...

Retrieve the bounding rectangle of a div that has the CSS style `display: contents` using the getBoundingClientRect

My objective is to apply styling and obtain the bounding box of an entire "row" within a CSS grid, including features like highlighting when hovering over it. To achieve the styling aspect, I make use of the display: contents property, so that the styles ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

When using Nuxt auth, I receive a Bearer token for authentication

During the implementation of an authentication system using nuxtjs/auth, I encountered a challenge where the token sent from the backend appears as Bearer token... However, upon processing by nuxtjs/auth, another 'Bearer' is added to the beginni ...

React does not play well with the Sendgrid Node.js library

Seeking assistance with integrating node.js to handle email sending on my website. Interested in having the email form immediately send upon submission, rather than using the standard "mailto" action. Utilizing Sendgrid as the email service for API and ser ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

What are some ways to implement pagination on a website?

Struggling to implement pagination without Laravel? You're not alone. The challenge lies in creating a cycle that displays the correct number of pages, with each page containing 10 posts out of a total of 98. While you've managed to calculate the ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Using Selenium Web Driver to extract information from Google's knowledge graph

Currently utilizing the Ruby Selenium web driver, my goal is to extract content from the Google Knowledge Graph located on the top right-hand side of the search results page. This element is within the <div class="xpdopen"> section. @driver = Seleni ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

retrieving information via AJAX call using jQuery

I've been tasked with customizing a book website, and I'm trying to integrate reviews from the Goodreads API. However, my Ajax request isn't returning any data. Here is the code snippet: $.ajax({ 'type': 'GET', & ...

What is the best way to present a unique page overlay specifically for iPhone users?

When browsing WebMD on a computer, you'll see one page. However, if you access it from an iPhone, not only will you be directed to their mobile page (which is easy enough), but they also display a special overlay with a "click to close" button prompti ...

Mastering the Art of Managing AJAX Requests with EXTJS

I have a code to send an AJAX request that appears to be functioning correctly under firebug, sending the correct parameters: Ext.Ajax.request({ url: 'test', params:{name: "bunya"}, success: function(resp){ ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Why does the hashtag keep popping up every time I launch the Bootstrap Modal?

I can't figure out why this keeps happening. I researched how to eliminate hashtags from the URL and found multiple solutions. However, none of them proved to be helpful as they only removed the hashtag, requiring a page refresh which still didn' ...

What is the best way to showcase the organized values according to their attributes?

How can I sort and display values based on their properties? For example, I want to only show the likes and convert them back into an object so I can use them as properties. I apologize for the previous edit, this is the updated version with a working sim ...

What is the best way to ensure that all of my images are the same size?

I've been working on making my pictures of varying resolutions the same size here, but no matter what I try, it just doesn't seem to work. Here is what I'm getting: . When I change the state to 1, 2, 3, or 4, I want it to look like this: her ...

Get the file from the web browser

Hey there, greetings from my part of the world. I have some straightforward questions that I'm not sure have simple answers. Currently, I am working on a web application using the JSP/Servlet framework. In this app, users can download a flat text fil ...