import { useEffect, useRef, useState } from "react"

type State = {
    data: string | null
    loading: boolean,
    error: boolean | null
}


export const useFetch = (url: string): State => {

    const isMounted = useRef(true);
    const [state, setState] = useState<State>({ data: null, loading: true, error: null })

    useEffect(() => {
        return () => {
            isMounted.current = false;
        }
    }, [])


    useEffect(() => {

        setState({ data: null, loading: true, error: null });

        fetch(url, {
            headers: {
                'Authorization': `Token`
            }
        })
            .then(resp => resp.json())
            .then(data => {

                if (isMounted.current) {
                    setState({
                        loading: false,
                        error: null,
                        data
                    });
                }

            });

    }, [url])

    return state;
}
