skip to Main Content

I’m trying to call a post request from Next.js app. However, there is a cancel button to stop the post request. I’m trying abortController with Axios (v1.4.0) to stop the post request.

When I’m calling the cancel function ‘cancelUploadHandler’ it’s being called, but request isn’t stopping.

  const abortController = new AbortController()

  const completeHandler = async () => {
      try {
        const response = await axios.post(
          process.env.APP_URL + "post-url/",
          data,
          {
            onUploadProgress: (progress) => {
              console.log(progress)
            },
            withCredentials: true,
            signal: abortController.signal
          }
        );
        return response.data;
      } catch (error) {
        if (axios.isCancel(error)) {
          console.log("Request canceled:", error.message);
        } else {
          console.log(error)
        }
      }
  };

  const cancelUploadHandler = () => {
    console.log("CANCEL REQUEST")
    abortController.abort()
  }

2

Answers


  1. You can’t “undo” a network request that already happened. All the abort() does is to stop the asynchronous task related to the network in your JavaScript environment. As you can read on MDN:

    The AbortSignal interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object.

    If click the cancel button before the request has completed, you would enter the catch blog with an error. But for the server that’s called, nothing changes.

    Login or Signup to reply.
  2. We create an instance of AbortController and get the signal property from it.
    When making the fetch request, we pass the signal to the signal option of the fetch request.
    Later, if you want to abort the request, you can call the abort() method on the controller. This will cause the fetch request to throw an AbortError and reject the promise returned by fetch().

    import NavBarItem from "./NavBarItem";
    import Loading from "./Loading";
    import { Suspense } from "react";
    // Create an instance of AbortController
    const controller = new AbortController();
    const { signal } = controller;
    
    // Create a fetch request with the signal
    const url = 'https://example.com/api/data';
    const fetchData = async () => {
      try {
        const response = await fetch(url, {
          method: 'POST',
          signal: signal, // Pass the signal to the fetch options
          // Add other fetch options (e.g., headers, body)
        });
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('Fetch error:', error);
      }
    };
    
    // Call the fetchData function
    fetchData();
    
    // Later, if you want to abort the request
    controller.abort();
    
    function NavBar() {
      return (
        <div className="flex dark:bg-slate-600 bg-amber-100 p-4 lg:text-lg justify-center gap-6 mb-8 sm:mb-10">
        {/* useParam similarity --my pov */}
          <NavBarItem title="Trending" param="fetchTrending"/>
          <Suspense fallback={<Loading />}><NavBarItem title="Top Rated" param="fetchTopRated" /></Suspense>
        </div>
      );
    }
    
    export default NavBar;
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search