An issue of an infinite loop arises when utilizing the updated() lifecycle hook in VueJS

I am working on a VueJS application where I need to fetch a list of articles in one of my components. The logic is such that if the user is logged in, a specific request is made, and if not, another request is executed. Below is the snippet of code:

<script>
  import { getFollowersPosts } from './../services/post';

  export default {
    name: 'Home',
    props: {
      user: Object
    },
    data() {
      return {
        posts: []
      }
    },
    async updated() {
      if (this.user) {
        this.posts = await getFollowersPosts(1);
      }
    }
  }
</script>

The issue arises because the user prop is coming from the parent component and there is a delay before it is retrieved by the app. Once the user prop is available, the component updates triggering the backend request using getFollowersPosts(). However, when the request result is received, it updates the posts array causing the component to update again and creating an endless loop. This continuous updating also leads to the MySQL database connection closing unexpectedly.

Is there a way to prevent this infinite loop? My intention is simply to retrieve the list of articles without any issues.

Thank you.

tl;dr I am facing challenges with making a request that updates the component's data after a prop changes, leading to an infinite update loop. Using another lifecycle hook like created() would not allow me to access the user prop.

Answer №1

Keep an eye on changes to the user object and trigger the getFollowersPosts() request from there instead.

watch: {
    user: function (val) {
      if (val) {
        this.posts = await getFollowersPosts(1);
      }
    }
}

For more information on watchers, check out this link:

Answer №2

After struggling for hours to find a solution, I finally stumbled upon the answer right after posting my question.

I was able to make it work by incorporating a watcher in my code. It seems that the watcher is triggered only once when each prop is updated. Here's how my code looks now:

<script>
  import { getFollowersPosts } from './../services/post';

  export default {
    name: 'Home',
    props: {
      user: Object
    },
    data() {
      return {
        posts: []
      }
    },
    watch: {
      user: async function() {
        if (this.user) {
          this.posts = await getFollowersPosts(1);
        }
      }
    }
  }
</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

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

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 ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

Creating a variable by utilizing $index values within two nested v-for loops

For my project, I am attempting to organize the days of a month into a table using 2 v-for loops. To simplify my code, I am considering creating a t_index variable that would be equal to ((r_index - 1) * 7 + c_index) - 2, but I am unsure how to implement ...

The issue of the JQuery method failing to function properly on a button arises when the button is added

Upon loading a HTML page containing both HTML and JavaScript, the code is structured as shown below: <button id="test"> test button </button> <div id="result"></div> The accompanying script looks like this (with jQuery properly in ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

Guide on setting up Tailwind CSS and material-tailwind concurrently within the tailwind.config.js configuration file

I am looking to integrate both Tailwind and Material Tailwind in a Next.js 14 project. Below is my customized tailwind.config.ts file (already configured with Tailwind CSS): import type { Config } from 'tailwindcss' const config: Config = { ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Position the read more buttons in JavaScript at the bottom of the div

I designed three boxes in this section with content inside. To enhance the functionality, I added a feature that made the boxes smaller. Everything was functioning perfectly, but I encountered an issue with the alignment of the buttons at the bottom. Is th ...

Effortlessly Retrieve Initial Data from Ajax in Vue3 using Composition API

After extensively researching different approaches, I am leaning towards using the Vue3 composition API in its "setup" form for future compatibility. However, I am encountering a significant amount of variability across these approaches. My current form i ...

Accessing parent properties in the setup() function of Vue 3 using the composition API. How can you retrieve the context parent

Currently facing a dilemma with Vue 3 (alpha 4): Within the setup() function, I am attempting to access the parent component. According to the guidance provided on , the parent should be accessible via the context argument, either as a property of context ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

sharing data between two node.js servers using http

I am currently working on integrating two node.js/express servers that communicate with each other using HTTP. One of the servers, known as server A, is responsible for handling file upload requests from the browser. My goal is to seamlessly transfer any u ...

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

Setting an ID attribute with EditorFor

I have been working with a template for Views and utilizing a lot of JQuery to extract input from an EditorFor. Due to this, I prefer sticking with my current setup using EditorFor instead of something like <input type="text"> I recently added a dat ...

The use of a <button> element in a React App within a Web Component with Shadow DOM in Chrome disables the ability to highlight text

An unusual problem has arisen, but I have a concise example that demonstrates the issue: https://codesandbox.io/s/falling-architecture-hvrsd?file=/src/index.js https://i.stack.imgur.com/CkL4g.png https://i.stack.imgur.com/nDjuD.png By utilizing the divs ...

Tips for preventing the need to re-render every child component generated by the v-for directive

Here is a paragraph about the list of child components: <question-list-item v-for="(item, index) in questionListParsed" :key="item.id" :both-question="item" :class-id="classId" ...

Adjusting the appearance of a JavaScript element based on its hierarchy level

Currently, I am utilizing Jqtree to create a drag and drop tree structure. My main goal is to customize the appearance of the tree based on different node levels. Javascript Tree Structure var data = [ { name: 'node1', id: 1, chi ...