Greetings! I am currently retrieving an array of posts from my express API in the Home.vue file, which is secured by route guards.
<script>
export default {
created() {
this.$store.dispatch('fetchPosts')
}
}
</script>
The fetchPosts action looks like this:
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)
}
}
Within this action, a mutation is committed to set the posts object to res.data. I specifically want the fetchPosts function to only run when a user logs in, as there is a mutation that adds a post to the database and updates the posts state when a user adds a new post. However, when routing back to the home screen, the created() hook runs again, causing data to be re-fetched with each post request. The app still functions properly but could be optimized for efficiency. How can I enhance my application to resolve this issue?