1
\$\begingroup\$

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>
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Oct 18, 2018 at 22:27
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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 to setInterval().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

answered Nov 12, 2018 at 19:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.