概要
ページ遷移をした際にレスポンスが返ってきていないものをキャンセルする方法をメモします。
今回はfetchを利用してキャンセルしたいと思います。
実装
store
store/comment.js
const state ={
controller: new AbortController()
}
const getters = {
controller: state => state.controller ? state.controller: '',
}
const mutations = {
setController(state, controller){
state.controller = controller
}
}
const actions = {
async getComment({commit, state}, {id}){
const { signal } = state.controller
const params = {
id: id
}
const query_params = new URLSearchParams(params)
await fetch(`/api/comment?${query_params}`, { signal })
.then(result=> result.json())
.then(result=>{
//処理を記述
}).catch(error=>{
//処理を記述
})
},
//キャンセル処理
cancel({state}){
state.controller.abort()
console.log('キャンセル完了')
},
}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
Vue
comment.vue
<script>
export default{
beforeRouteLeave(to, from, next){
//ページを去った時にcancel()をする
this.$store.dispatch('comment/cancel')
//キャンセル処理後にstate.controllerにnew AbortController()を設置
this.$store.commit('comment/setController', new AbortController())
next()
}
}
</script>