How to deal with the slow API response

Some of you have reported that it takes a while for the data to be loaded from the API, and this becomes annoying when you're debugging and have to refresh the page constantly.

There is a solution to this which will allow your app to store the data only once and keep a copy of it until the user closes the browser tab.

Look at the View Source of this page to see the Javascript code. It makes use of an HTML5 API, called localStorage.

To test it, refresh the page. Then close the tab, see what happens, and refresh again.

Here are the relevant lines of code involving localStorage.

// store data in the localStorage
localStorage.setItem("coursesData", JSON.stringify(items));

  // retrieve data that has been stored in the localStorage 
coursesDataStr = localStorage.getItem("coursesData");

// convert data to JSON, because when stored it has been stringified
coursesDataJSON = JSON.parse(coursesDataStr);
  

For the CS110 course, I have written some notes to explain localStorage and how it can be used to store things locally in the browser.

If you are curious about the "event binding" mentioned in the code comments, especially the "onunload", I have some notes on that too, together with an example of building a bookmarking application for reading. Check it out.