0

I am trying to optimize my react code by fixing any memory leaks. For this i am using createAsyncThunk canceling-while-running.

I am successful in implementing this using useEffect where I dispatch a reducer to request, when the component mounts and i could automatically trigger abort() signal when the component unmounts using the return of useEffect. Refer the below code:

useEffect(() => {
    const promise = dispatch(getIssuedBooks())
    return promise.abort()
  }, []);

But i have other reducers which get dispatched on onClick events. Refer the code below:

const handleRequest = (id) => {
   dispatch(requestBook(id))
}

My problem is when component unmounts how do i abort from this request. I tried some things but it did not work out. Please help. Thanks in advance.

Roshan Shetty
  • 267
  • 1
  • 13

1 Answers1

0
const controller = new AbortController();
const signal = controller.signal;

const url = "video.mp4";
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

function fetchVideo() {
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 23 '23 at 08:49