Skip to content
Advertisement

Best place to fetch data for authed users in Vue app?

Hi I’m fetching a arrays of posts from my express API in the Home.vue which is protected by route guards.

<script>
export default {
  created() {
    this.$store.dispatch('fetchPosts')
  }
}
</script>

fetchPosts action:

async fetchPosts(context) {
  try {
    const res = await api.get('/posts', {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    context.commit('SET_POSTS', res.data)
    context.commit('SET_ERROR', null)
  } catch(err) {
    console.log(err.response.data)
    context.commit('SET_ERROR', err.response.data)
  }
}

In my action I commit a mutation which sets the posts object to res.data. I only want to fetchPosts when user logs in since I have a mutation which adds the post to the db and updates the posts state, when user adds a post. But because I route back to the home screen this causes the created() hook to run again, re-fetching data on each post req. App of course work fine but could be more efficient. What can I do to resolve better enhance my app?

Advertisement

Answer

You could check that you do not already have the state populated.
If it’s empty make the API call, otherwise do nothing.

Having guards is a good thing. Depending of your app and the way you want to handle authed users, you could also wire a global middleware to your router. This will add more generic code and could be used on several places, hence less errors/duplication.

Here is an interesting article about this: https://markus.oberlehner.net/blog/implementing-a-simple-middleware-with-vue-router/

The rest of your code looks fine!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement