CodingNic

Persistence & Application Preferences

Load History on Startup

Persistence & Application Preferences 25 min read

Load History on Startup

Task

Restore saved history when the application starts.

Open

Open:

js/history.js

Add:

javascript
function loadHistory() {
  const saved = localStorage.getItem(HISTORY_KEY);

  if (!saved) {
    return [];
  }

  try {
    const history = JSON.parse(saved);
    return Array.isArray(history) ? history : [];
  } catch {
    return [];
  }
}

Then, during application startup, restore the state:

javascript
calculator.state.history = loadHistory();
renderHistory(calculator.state.history, historyContainer);

Test

  1. Perform two or three calculations.
  2. Refresh the browser.
  3. Confirm the history is still visible.
  4. Close and reopen the page if your local development setup allows it.
  5. Confirm the history remains.

Checkpoint

The calculator now restores saved history when the application starts.