The Vue.js updated hook causing unnecessary page rerenders even when there are no changes in the state

Seeking to retrieve data from an api and utilize updated() to trigger a rerender upon a change in the state that stores the fetch url. However, encountering an issue where the updated hook continues to render even when there is no alteration in the state.

Attempting to monitor state changes through click events, only to observe updates occurring without any real change in the state.

Here is the template code:

  <template>
    <div class="overlay" ref="overlay">
    </div>
    <div class="home">
      Hello People
     
      <form @submit.prevent="handleSearch">
        <input type="text" name="search" v-model="search" />
        <button type="submit">Search</button>
      </form>
      <select name="" id="select" v-model="select" v-on:change="selectclass">
        <option value="">Default</option>
        <option value="Breaking+Bad">Breaking Bad</option>
        <option value="Better+Call+Saul">Better call saul</option>
      </select>
      <div class="charlist">
        <div class="gridlist" v-for="char in chars" :key="char.id">
          <div>
            <div class="subgrid">
              <img class="img" :src="char.img" alt="alt">
              <p> {{ char.name }} </p>
              <router-link :to="{ name: `Details`, params: {id: char.char_id} }">
              <button> more</button>
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>

And the script:

  <script>
    export default {
      name: 'Home',
      components: {
    
      },
      data() {
        return {
          url: 'https://www.breakingbadapi.com/api/characters?limit=10&offset=10',
          search: "",
          select: "",
          chars: []
        }
      },
      methods: {
        handleSearch() {
          this.url = `https://www.breakingbadapi.com/api/characters?name=${this.search}`
        },
        selectclass() {
          this.url = `https://www.breakingbadapi.com/api/characters?category=${this.select}`
        },
        getData() {
          fetch(this.url)
            .then(res => res.json())
            .then(data => {
              this.chars = data
              console.log(this.chars)
            })
        }
      },
      mounted() {
        this.getData()
      },
      updated() {
        console.log(this.url)
        this.getData()
      }
    }
  </script>

Answer №1

It appears that there is a recurring loop happening in the code - Component Inits -> Gets Data -> Updated is called, triggering getData again, leading to a continuous cycle.

Vue seemingly re-renders whenever a variable value is changed, regardless of whether the old and new values are the same.

To break the loop, it is recommended to invoke getData within the functions selectclass and handleSearch. This should help avoid the repeating loop issue.

Check out this warning in the documentation: https://vuejs.org/api/options-lifecycle.html#updated

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

"Encountering issue with jQuery $.ajax DELETE not triggering then() function

I have implemented some code within a Chrome extension that effectively utilizes the then() method from the xhr response when using $.ajax. if (request && request.action === "updateTask") { $.ajax({ type: "PUT", url: config.upda ...

Google Maps is experiencing difficulties maintaining its longitude and latitude coordinates within the Bootstrap tabbed user interface

I implemented ACF's Google Map to display a map on my webpage. I followed the instructions closely and made some minor modifications to the map js for styling purposes. One key change I had to make was in this section to ensure the map loads correctly ...

An error occurs even before any Components are rendered, with a TypeError stating that the property 'type' cannot be read because it is undefined

I'm facing an issue with my Redux App where the first component (App.js) is not rendering due to continuous errors. The reducer mentioned below is being triggered at some point without any action, causing the compiler to interpret action as null and f ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

Authenticate the user by comparing the entered username and password with the database records. If they match, proceed to redirect the user to their profile page. Otherwise, log

Attempting to complete this assignment which involves a user entering their username and password. If the information matches what is stored in the database, the user should be redirected to their profile page where a personalized greeting message is displ ...

Connecting a dynamically assessed function on the $scope to a service

Within my code, there is a function called make_value_summary that has the capability to generate a generic summary of various fields within the $scope. By applying this function, I am able to create location_summary, which is then linked to the view using ...

Having trouble retrieving the tag name, it seems to be giving me some difficulty

I have two separate web pages, one called mouth.html and the other nose.html. I want to retrieve a name from mouth.html and display it on nose.html when a user visits that page. How can I accomplish this using JavaScript? Here is the code snippet from mou ...

Extracting necessary data from a JSON file and generating a new JSON file with the selected information

My task involves parsing a JSON file to extract events that fall within a specified start and end time provided via an HTTP GET request. The goal is to return these filtered events as a new JSON-encoded response. Despite brainstorming two potential solutio ...

Tips for transferring a JSON object from an HTML document to a JavaScript file

Here is the code snippet: <script id="product-listing" type="x-handlebars-template"> {{#each productsInCart}} <tr> <td> <div class="imageDiv"> <img ...

Which Client-Side JavaScript Frameworks Pair Seamlessly With Node.js, Express.js, and socket.io.js?

Currently, I am in the process of developing a web application utilizing Node.js, Express.js, and socket.io.js on the server side. Are there any front-end frameworks (such as Agility, Angular, Backbone, Closure, Dojo, Ember, GWT, jQuery, Knockback, Knocko ...

Unspecified tag name attribute in Vue that can be accessed in the browser

At the moment, I have encountered an issue with a selector in Vue returning undefined for {{ lens.price }}. However, when I use a = lens[1].getAttribute('price') in the browser console, it correctly displays the value as "0". Why is Vue showing ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

Adding a child node before an empty node in Chrome with JavaScript Rangy

When attempting to insert a node before an empty element at the start of another element, a problem was noticed. Here is the initial setup: <p>|<span />Some text</p> By using range.insertNode() on a Rangy range to add some text, Chrome ...

Develop a distinctive JavaScript solution that enables an image to appear in fullscreen upon loading the page, and then smoothly fade away after precisely

I have been trying to incorporate a feature on my Shopify frontage website where our logo appears fullscreen and then fades away or disappears after a few seconds, allowing people to access the rest of the website. However, I am facing difficulty in making ...

What is the top frontend framework and which one seamlessly integrates with various backend frameworks?

When it comes to frontend frameworks, JavaScript acknowledges three major players: React, Angular, and Vue.js. Each of these frameworks offers ease of understanding, learning, and implementation. Now the question arises - which one is most compatible wit ...

Can data be transferred from the template to the script using Vue.js? (Opposite of v-bind)

Is it possible to pass the current data in a v-for loop (in the template) to a function in methods? <li v-for="annonce in annonces"> <article> //For example, can I send annonce.categorie to the methods //object of the component t ...

Establish a connection to couchDB using JavaScript on the server side

I'm working on a piece of code that involves using Restify to set up a server in node.js and create specific routes. My goal is to interact with CouchDB by performing actions such as GET, POST, DELETE, and PUT. var restify = require("restify"); var s ...

Refreshing a DIV in Rails by reloading from model using a JavaScript function

Recently, I created a page displaying the number of Widgets a customer has. Below is the view written in Haml: #available = "Available widgets: #{@customer.widgets.unused.count()}" (The "unused" scope in the model displays available widgets). When a C ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...