Replies: 1 comment
-
import React from 'react'
import useAsyncEffect from '@n1ru4l/use-async-effect'
const useCachedImage = ({id, imageUrl}) => {
const [blob, setBlob] = React.useState()
const [error, setError] = React.useState()
useAsyncEffect(
function* (_, c) {
if (!id || !imageUrl) return
try {
const cacheRecord = yield* c(
idb.get(id)
)
const cacheStatus =
!cacheRecord
? CACHE_MISS
: isFresh(cacheRecord.t)
? CACHE_FRESH
: CACHE_STALE
if (cacheStatus !== CACHE_MISS) {
setBlob(cacheRecord.blob)
}
if (cacheStatus === CACHE_FRESH) return
const responseBlob = yield* c(
fetch(imageUrl).then(response => response.blob())
)
setBlob(responseBlob)
idb.set(id, {t: now(), blob: responseBlob})
} catch(e) {
console.error(e)
setError(e)
}
},
[id, imageUrl]
)
return {blob, error}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
llaenowyd
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I want to add a durable local cache, and not send a request at all if the cached value is fresh.
I thought of a few ways to approach it. One way that fits in pretty well would be to write a fetcher like,
I guess this probably won't work. What would be a better way to set this up?
Edit: Perhaps instead of
swr
, in this case,@n1ru4l/use-async-effect
Still, though, interested in a simpler way to re-think it.
Beta Was this translation helpful? Give feedback.
All reactions