I’m new to PWA and am trying out an example. The rest works well except when it tries to fetch from the cached API response. Below is the excerpt of the app.js I am using. When it tries to fetch from the cached response, this line: var data = await cacheResponse.json();
, gives the error listed in the title. I have checked the cached response and the API response, they are the same. Could it be the scope? If so, how should I address it? Thanks for any suggestion.
document.getElementById('fetch-data').addEventListener('click', fetchData);
async function fetchData() {
const apiUrl = 'https://jsonplaceholder.typicode.com/todos/1';
const cacheName = 'api-cache';
var cache = await caches.open(cacheName);
var cachedResponse = await cache.match(apiUrl);
if (cachedResponse) {
console.log('Serving from cache: ', cachedResponse);
var data = await cacheResponse.json();
displayData(data);
} else {
try {
var response = await fetch(apiUrl);
console.log('Serving from API: ', response);
cache.put(apiUrl, response.clone());
var data = await response.json();
displayData(data);
} catch (error) {
console.error('Failed to fetch data: ', error);
}
}
}
function displayData(data) {
document.getElementById('data').textContent = JSON.stringify(data, null, 2);
}
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered with scope: ', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed: ', error);
});
});
}
I’m expecting the cached API response will work and print the response on screen; the same as when the API made an actual call.
Vins is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ah, I just realized that there is a typo. It should be cachedResponse.json()
, instead of cacheResponse.json()
. Silly me.
Please close this question.
Vins is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.