0

This is my cache "component":

// imports

const useCache = (cacheName: string, url: string) => {
    const cacheArray: Array<Object> = []

    const getAllCaches = async () => {
        const cacheNames = await caches.keys();
        for (const cname of cacheNames) {
            const cacheStorage = await caches.open(cname);
            const cachedResponse = await cacheStorage.match(url);
            const cdata = await cachedResponse?.json()

            cacheArray.push({name: cname, data: cdata})
        }
    }

    useEffect(() => {
        getAllCaches()
            .catch(err => console.log(err))
    }, [])

    const addCache = (response: any) => {
        const data = new Response(JSON.stringify(response));
        if ('caches' in window) {
            caches.open(cacheName).then((cache) => {
                cache.put(url, data);
            });
        }
        const finalData = {name: cacheName, data: response}
        cacheArray.push(finalData)
        return data
    }

    const getCache = (cacheName?: string) => {
        if (cacheName) {
            return cacheArray.filter((i: any) => i.name === cacheName)[0]
        }
        else {
            return cacheArray
        }
    }

    const removeCache = (cacheName: string) => {
        caches.delete(cacheName).then(function (res) {
            return res;
        });
    }

    return [
        getCache as (cacheName?: any) => any,
        addCache as (response: any) => any,
        removeCache as (cacheName: any) => any
    ]
};

export default useCache;

Now here's code in my home component:

    const [getCache, addCache, removeCache] = useCache("user", "http://localhost:3000")

    useEffect(() => {
        console.log(getCache())
        console.log(getCache()[0])
        console.log(getCache().length)
    // the rest of code, not matter

and when I run home component (with vite and preact) it logging me Array, then unfedinfed, then 0 (but second should return object, and third should return 1) also I attached a screen from console.enter image description here

Why it's returning me undefined and 0 length when it should return object and 1?

I'm using preact, vite, newest nodejs, typescript

  • You could try adding some logging to all inner functions, as well as `useEffect`, that should give you some info about the order of execution and might provide some clues. – tromgy Sep 03 '22 at 22:21
  • You have two major problems. [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) you're trying to access a value before it's available. And your `cacheArray` is basically always empty. Everything that you ever write to that `cacheArray` is pointless because right after the render you throw it away and on the next render you start over with `const cacheArray: Array = [];` – Thomas Sep 03 '22 at 23:03
  • @Thomas Makes sense. So `cacheArray` is always empty but since on the first `getCache()`, he's returning a reference of `cacheArray`, it also updates it in the `console.log` after the async is resolved? And since in the `getCache()[0]` and `getCache().length`, he's already trying to access `[]`, it returns him `undefined` and `0`. Since `undefined` and `0` aren't references to an array, it doesn't update in the `console.log` even after the async is resolved. Is that correct? – Jeffrey Ram Sep 03 '22 at 23:14
  • @JeffreyRam The console doesn't show you the object at the time you logged it, it shows you the object at the time you look at the log. [Is Chrome’s JavaScript console lazy about evaluating objects?](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects). This may be a good thing at times, but not when you try to find timing bugs/issues while mutating an object. – Thomas Sep 03 '22 at 23:21

0 Answers0