Search code examples
javascriptreactjsamazon-web-servicesaws-amplify

Not able to cancel REST(POST) request of AWS amplify in react


I have following code snippet which generates POST request using aws amplify api. I am storing API.post promise inside promiseToCancel variable. and when user clicks on cancel button I am calling cancelRequest().

promiseToCancel variable has promise object in pending state which I am passing to API.cancel().however this api request not getting cancelled. and I don't see any errors on console also.

I am using aws-amplify version 3.3.13.

import API from "@aws-amplify/api"

let promiseToCancel;

const post = (path, body, options) =>{
  try {
    ...
    ...
    promiseToCancel = API.post().then(()=>{

    }).catch(()=>{
  
    })
    ....
    ....

  }
  catch(){
    
  }
}

const cancelRequest = () => {
  API.cancel(promiseToCancel, 'request cancel message')
}

can someone please help me to identify what is wrong with this? Not sure but I think some scope issue is causing this behavior.


Solution

  • I changed API.post() as below and its working. Issue was with how promise has written and we are storing reference.

    try {
    ...
    ...
    promiseToCancel = API.post();
    promiseToCancel.then(()=> {
    
    }).catch(()=>{
    
    })
    ....
    ....
    
    } catch(){
    
     }