Search code examples
javascriptjsoncachingfetchlocal-storage

Save JSON in Local Storage after the fetch


Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.

I was thinking of setting up two fetch() functions, and this is what I have:

   fetch(url + id)
        .then((response) => {
            localStorage.setItem('myResponse', response);
        })              
        .catch((error) => {
            console.log(error);
        })

Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.

  if(localStorage) {
     createHTML(localStorage.myResponse);
  } else {
     fetch(url + id)
         .then(response => response.json())
         .then(data => createHTML(data))
  }    

But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows Promise {<pending>}.

I've tried to make something out of that, but without results...any help much appreciated!


Solution

  • response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.

    fetch(url + id)
            .then( response => response.json() )
            .then( json => {
                localStorage.setItem('myResponse', JSON.stringify(json));
            })
    

    Or with the async/await syntax :

    const response = await fetch(url + id);
    const json = await response.json();
    localStorage.setItem('myResponse', JSON.stringify(json));