import React, {useContext, useState} from 'react'
import {AxiosResponse} from "axios";
import AuthContext from "../context/auth-context";

interface Cache {
    [key: string]: AxiosResponse
}
let cache:Cache = {};


export const useCachedFetch = () => {

    const ctx = useContext(AuthContext)
    const [status, setStatus] = useState('idle');

    const fetchCachedData = async (apiCall:any) => {

        setStatus('fetching');
        if (cache[apiCall.name]) {
            const response = cache[apiCall.name];
            setStatus('fetched');
            return response
        } else {
            const response = await apiCall()
            cache[apiCall.name] = response; // set response in cache;
            setStatus('fetched');
            return response
        }
    };

    return { status, fetchCachedData};
};

export const clearCache = () => {
    cache = {}
}

