createAsyncThunk not working Canceling While Running

Viewed 43

Abort is not working on createAsyncThunk. I am trying to abort the dispatch method while dependencies change in useEffect hooks. In the below code, I try to call API on btn click with help of a counter and try to abort the previous call also. But I didn't get the promise of a dispatch method. It is getting undefined. Code: `

const [counter, setCounter] = React.useState(0);
const handleClick = () => {
    setCounter(counter + 1);
  };

React.useEffect(() => {
       const promise = getDataAction();
        return () => {
          if (promise) promise.abort();
        };
}, [counter, getDataAction]);
    
return (
        <div className={styles.home_container}>
          <div className={styles.btn} onClick={handleClick}>
            Click
          </div>
        </div>
);

const mapDispatchToProps = (dispatch) => {
  return {
    // dispatching plain actions
    getDataAction: () => dispatch(getData()),
  };
};

`

1 Answers
const abort = React.useRef();
React.useEffect(() => {
    // Dispatching the thunk returns a promise
    abort.current = new AbortController();
    dispatch(getDataAction({ signal: abort.current.signal }));
 
    return () => {
      abort.current.abort();
     
    };
  }, [search]);
Related