Skip to content

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.

export default {
  created() {

fetchPosts action:

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

In my action I commit a mutation which sets the posts object to 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?


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:

The rest of your code looks fine!