Within a History view, I pull down history from backend server by calling the Vuex action in created(), and pass the data to the history table using a computed function, history() that accesses the history module state.
The problem is, each time I return to the History view, a new requests to the server is made due to calling the action in created().
How can I setup so the call is made the first time the view is accessed, and rely on history state for subsequent visits to this view?
History.vue
<script>
import { mapActions } from "vuex";
export default {
name: "History",
data() {
return {
// data
};
},
methods: {
...mapActions(["fetchHistory"]),
refresh() {
this.fetchHistory()
},
computed: {
history() {
return this.$store.state.history.records;
},
},
created() {
this.refresh();
},
};
</script>
historyModule.js
async fetchHistory({commit}){
await axios.get('api/history')
.then((response) => {
commit('setHistory', response.data)
return Promise.resolve();
})
.catch((error) => {
commit('setHistory', [])
return Promise.reject(error)
})
}
If history.records is array you can check length before dispatching actions:
created() {
if(!this.$store.state.history.records.length) this.refresh();
},
If you want this pattern to work across components, you can add the same behavior to the Vuex action instead of to the created hook. This will also keep all of your Vuex behaviors inside of your store code.