Created
February 9, 2022 02:44
-
-
Save wkei/0fdea5ae0b656696b8976ece20ce5747 to your computer and use it in GitHub Desktop.
react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fetch with caches api | |
import { useState, useEffect, useRef } from 'react'; | |
export default function useCacheFetche(cacheId: string) { | |
const fetcher = <T>(url: string) => { | |
const [data, setData] = useState<T | null>(null); | |
const [error, setError] = useState(null); | |
const cacheRef = useRef<Cache | null>(null); | |
useEffect(() => { | |
const run = async () => { | |
cacheRef.current = await caches.open(cacheId); | |
const res = await cacheRef.current.match(url); | |
if (res) { | |
setData(await res.json()); | |
} else { | |
await cacheRef.current.add(url); | |
const res = await cacheRef.current.match(url); | |
res && setData(await res.json()); | |
} | |
}; | |
try { | |
run(); | |
} catch (error: any) { | |
setError(error); | |
} | |
}, []); | |
return { data, error }; | |
}; | |
const clean = () => caches.delete(cacheId); | |
return { | |
fetcher, | |
clean, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment