skip to Main Content

Started learning axios and I’m loving it!

Quick question, could not find an answer for it, maybe there is non.

In jQuery ajax there is a method called ajaxComplete, I was wandering if there is an equivalent in axios?

2

Answers


  1. axios uses promises. You can use

    axios.get(url,[options]).then(res=>{
    /* hande it here */
    })
    

    Check out how js promises work if you do not have a basic knowledge https://web.dev/promises/

    For global handling axios event this may help https://auralinna.blog/post/2019/global-http-request-and-response-handling-with-the-axios-interceptor/

    Login or Signup to reply.
  2. No there is not. jQuery’s $.ajax has a function build in where it fires an event when a request has been finished. This is the ajaxComplete event.

    Axios does not have such behavior, but you could build your own with the CustomEvent interface. Or / and assume that there is a method axiosSuccess on the document and call that.

    const axiosGet = async url => {
      try {
        const response = await axios.get(url)
        const axiosSuccessEvent = new CustomEvent('axiossuccess', {
          detail: { url, response }
        })
        document.dispatchEvent(axiosSuccessEvent)
        if (typeof document.axiosSuccess === 'function') {
          document.axiosSuccess({ url, response })
        }
        return response
      } catch (error) {
        console.log(error)
      }
    }
    

    And then listen for your own event on the document.

    document.addEventListener('axiossuccess', event => {
      const { detail } = event
      const { url, response } = detail
      console.log(url, response)
    })
    
    document.axiosSuccess = ({ url, response }) => {
      console.log(url, response)
    }
    
    axiosGet('https://stackoverflow.com/questions/63998921/')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search