I am fetching the friend list for a chat application using a Vuex store. I need to dispatch the getter via an interval. Is there a best practices way to do this?
<template>
<aside class="friend-list">
<h5 class="whos-online">Who's Online</h5>
<ul class="users">
<UserListItem v-for="user in friendList" :user="user" :key="user.user_id" />
</ul>
</aside>
</template>
<script>
import UserListItem from './UserListItem'
import { mapGetters } from 'vuex'
export default {
name: 'FriendList',
components: {
UserListItem,
},
created() {
this.fetchFriendList()
setInterval(this.fetchFriendList, 3000)
},
destroy() {
clearInterval(this.fetchFriendList)
},
methods: {
fetchFriendList() {
console.log(this.friendList)
this.$store.dispatch('chat/fetchFriendList')
}
},
computed: mapGetters({
friendList: 'chat/friendList'
}),
}
</script>
1 Answer 1
Responding to your question
Is there a best practices way to [dispatch the getter via an interval]?
You could consider using requestAnimationFrame()
(read more about using that with setInterval()
in articles like this one) but that might be overkill since you are just updating a list.
Another option to consider is using websockets (presuming your server-side would support it). That way the client-side could be notified of updates to the list instead of having to request them periodically.
Bug in the sample code
The sample code shows these methods:
created() { this.fetchFriendList() setInterval(this.fetchFriendList, 3000) }, destroy() { clearInterval(this.fetchFriendList) },
However, clearInterval()
takes an intervalID
as a parameter, not a function reference.
Parameters
intervalID
The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call tosetInterval()
.1
So instead of passing the method reference this.fetchFriendList
, pass an identifier returned from the call to setInterval()
in the created
method.
1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval#Parameters
Explore related questions
See similar questions with these tags.