Reputation: 707
I have a simple VueJS app. In one of my components, I'm trying to retrieve a list of articles. If the user is logged in, I make a specific request. Otherwise, I make another one. Here's my 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 thing is, the user
prop comes from the parent component, and it takes some time before the app retrieves it. Once the user
is retrieved, it updates the component, then I'm able to make the request to the backend with getFollowersPosts()
since I now have user
.
However, once I get the request result, I need to update the posts
array. This causes the component to update again, and start all over again. Now what I get is the component updating indefinitely, and even worse, the MySQL databases ends up closing the connection.
Is there a way to avoid that ? I just want to retrieve the list of articles, and that's it !
Thanks.
tl;dr I'm trying to make a request that updates the component's data after a prop updates, but it causes the component to update infinitely. If I use another lifecycle hook like created()
, I won't be able to retrieve the user
prop.
Upvotes: 3
Views: 3165
Reputation: 111
You should rather watch for change on the user object and make the getFollowersPosts() request there.
watch: {
user: function (val) {
if (val) {
this.posts = await getFollowersPosts(1);
}
}
}
You can read more about watchers here: https://it.vuejs.org/v2/guide/computed.html
Upvotes: 4
Reputation: 707
Wow, I've been struggling for hours to find an answer, and right after posting my question I ended up finding the solution.
So I got it to work using a watcher. I guess the watcher is called only once for each prop that's updated. Here's my code 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>
Upvotes: 2