Vuex store problem


#1

Hi,

I am writing vue app with vuex where I need to display users statuses.
They could be “online”, “offline”, “unknown”. I don’t need to fetch statuses for all users at once, I need to be able to fetch the status per user. And since the statuses frequently change, I need to store them for limited time, then delete.

So, I am trying to use following parts:

  1. Vuex store
const store = new Vuex.Store({
state: {
    statuses: {}
},
mutations: {
    updateUserStatus: (state, message) => {
        state.statuses[message.username] = message.status
        // reset state after timeout (30 seconds)
        setTimeout(function() {
            delete state.statuses[message.username]
        }, 30000)
    }
}
})
  1. Frontend element which displays user statuses and triggers fetching of status:
<template>
    <span @click.native="fetchUserStatus(username)">
     {{ statuses[username] }}
    </span>
</template>
<script>
export default {
    computed: {
        statuses: function() {
            return this.$store.statuses
        },
    }
}
</script>    

fetchUserStatus() is a simple function which calls api and runs ‘updateUserStatus’ mutation

So ideally user should see the following behaviour:

  1. the page is loaded, user sees “unknown” state inside a span.
  2. user clicks on an element, updateUserStatus() is called which changes the state to “online”
  3. 30 seconds pass, status should change back to “unknown”

How do i display “unknown” status for a user when i yet don’t have such info inside a store ?


#2

Try this:

<template>
    <span @click.native="fetchUserStatus(username)">
     {{ statuses[username] || 'Unknown' }}
    </span>
</template>