I am receiving images URLs from an API response and I want to cache each of those images. I tried just using cache.addAll but it does not work because the images are an opaque response. I am considering fetching each image using fetch
and having the routes cache them but I am not sure as to whether this would be the best way. Are there any other better alternatives?
Asked
Active
Viewed 1,264 times
0

AviatingFotographer
- 318
- 2
- 12
1 Answers
2
There's some guidance in this Stack Overflow answer that explains how to cache opaque responses; the gist of it is:
const request = new Request('https://third-party-no-cors.com/', {
mode: 'no-cors',
});
// Assume `cache` is an open instance of the Cache class.
fetch(request).then(response => cache.put(request, response));
The caveat is that your code has no way of knowing whether you're caching a valid response, or a HTTP 404 or some other error.

Jeff Posnick
- 53,580
- 14
- 141
- 167
-
Where should I do this? Inside my service worker or inside my React component, or some other place? – AviatingFotographer Feb 13 '21 at 20:30
-
1Either. It's up to you. The Cache Storage API and Fetch are both available in a SW or web page. – Jeff Posnick Feb 14 '21 at 03:11