Ky request cancellation not working on unmount

225 Views Asked by At

I'm using Ky to make requests. I want to cancel the request in case the component unmounts. I have this code, where I'm using useEffect hook to send a signal to a function and cancel the request:

import React, { useEffect, useState } from 'react'
import ky, { HTTPError } from 'ky'

const MyComponent = (props) => {
    /**
     * Every time the StatisticalValidation instance changes retrieves its data from the backend
     */
    useEffect(() => {
        const abortController = new AbortController()

        if (props.selectedStatisticalValidation.id) {
            getStatValidationClinicalAttrs(abortController.signal)
        }

        /** On unmount aborts Ky's request */
        return () => {
            abortController.abort()
        }
    }, [props.selectedStatisticalValidation.id])

    /** Make a request. */
    const getStatValidationClinicalAttrs = (signal: AbortSignal) => {
        const searchParams = { /* ... */ }
        ky.get(url, { searchParams, timeout: 60000, signal }).then((response) => {
            response.json().then(() => {
                // ....
            }).catch((err) => {
                // ...
            })
        }).catch((err: HTTPError) => {
            // ...
        })
    }
}

But It's not working, the request keeps in progress even when the unmounting function is correctly executed and the signal's aborted prop is true.

Some important considerations:

  1. I tried with useRef but that didn't work either.
  2. If I create the AbortController inside the getStatValidationClinicalAttrs() and abort it in that function it works, as expected.
0

There are 0 best solutions below