how to cancel/abort ajax request in axios

前端 未结 8 710
广开言路
广开言路 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
    })
    

提交回复
热议问题