Cant cancel Axios post request via CancelToken

后端 未结 5 1906
悲哀的现实
悲哀的现实 2020-12-10 16:04

This code cancel GET requests but cant abort POST calls.
If i send GET requests first and i dont cancel them via abortAll method,they just finish by themsel

5条回答
  •  既然无缘
    2020-12-10 16:17

    Using inside componentDidMount lifecycle hook:

    useEffect(() => {
    const ourRequest = Axios.CancelToken.source() // <-- 1st step
    
    const fetchPost = async () => {
      try {
        const response = await Axios.get(`endpointURL`, {
          cancelToken: ourRequest.token, // <-- 2nd step
        })
        } catch (err) {
        console.log('There was a problem or request was cancelled.')
      }
    }
    fetchPost()
    
    return () => {
      ourRequest.cancel() // <-- 3rd step
    }
    }, [])
    

    Note: For POST request, pass cancelToken as 3rd argument

    Axios.post(`endpointURL`, {data}, {
     cancelToken: ourRequest.token, // 2nd step
    })
    

提交回复
热议问题