how to cancel/abort ajax request in axios

前端 未结 8 678
广开言路
广开言路 2020-12-05 06:19

I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline c

相关标签:
8条回答
  • 2020-12-05 07:02

    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
        })
        console.log(response.data)
        setPost(response.data)
        setIsLoading(false)
      } 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
    })
    
    0 讨论(0)
  • 2020-12-05 07:04
    import React, { Component } from "react";
    import axios from "axios";
    
    const CancelToken = axios.CancelToken;
    
    let cancel;
    
    class Abc extends Component {
      componentDidMount() {
        this.Api();
      }
    
      Api() {
          // Cancel previous request
        if (cancel !== undefined) {
          cancel();
        }
        axios.post(URL, reqBody, {
            cancelToken: new CancelToken(function executor(c) {
              cancel = c;
            }),
          })
          .then((response) => {
            //responce Body
          })
          .catch((error) => {
            if (axios.isCancel(error)) {
              console.log("post Request canceled");
            }
          });
      }
    
      render() {
        return <h2>cancel Axios Request</h2>;
      }
    }
    
    export default Abc;
    
    
    0 讨论(0)
提交回复
热议问题