LoginSignup
0
1

More than 3 years have passed since last update.

fetchを使ってパラメータつきリクエストをキャンセルする

Posted at

概要

ページ遷移をした際にレスポンスが返ってきていないものをキャンセルする方法をメモします。
今回は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>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1