import React, {ReactNode, useEffect, useRef} from 'react';
import {setAbortSignal} from "../API/axios";



/**
 * cancells all pending requests when component is unmount
 * returns a signal that needs to get passed to the axios requests that u want to be cancellable
 * for v2 --> add dependency array as parameter, so u can cancel requests not just on unmount...
 */

const useAbortController = (dependencies:any[] = []) => {

    const abortControllerRef = useRef<AbortController>(new AbortController());
    //WE SEND THE SIGNAL ON THE AXIOS REQUEST SO WE CAN CANCEL IT ON UMOUNT
    //THE DEPENDENCY ARRAY IS EMPTY SO IT CANCELS ON UNMOUNT
    useEffect(() => {
        const controller = abortControllerRef.current;
        setAbortSignal(abortControllerRef.current.signal)
        return () => {
            controller.abort();
            setAbortSignal(undefined)
        };
    }, [])


}

export default useAbortController;