Struggling to find a solution after reading several articles, I am working on fetching a large JSON
from an API and I want to cache the response in the localStorage
. The goal is for the script to check for an object with the requested ID in the cached JSON
when the page reloads. If the object is found, it should render the content from the cache. Otherwise, it should fetch the data from the API.
My initial approach involved setting up two fetch() functions:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Subsequently, I intended to check if there is data stored in the localStorage
. If data exists, it should be used to render the HTML content. If not, another fetch should be made to retrieve the data from the API:
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
However, when attempting to use JSON.stringify(response)
in the first fetch, the result appears as an empty object in the localStorage
. As for console.log(response.json());
it shows Promise {<pending>}
.
I have been unable to make progress with this issue. Any assistance would be greatly appreciated!