CodingNic

Persistence & Application Preferences

Save History to localStorage

Persistence & Application Preferences 20 min read

Save History to localStorage

Task

Save history whenever the calculator creates or clears history.

Open

Open:

js/history.js

Create a storage key and helper functions:

javascript
const HISTORY_KEY = 'calculator-history';

function saveHistory(items) {
  localStorage.setItem(HISTORY_KEY, JSON.stringify(items));
}

Call saveHistory() after adding a calculation:

javascript
saveHistory(calculator.state.history);

Also call it after clearing history:

javascript
saveHistory(calculator.state.history);

Why JSON?

localStorage stores strings. JSON.stringify() converts the history array into a string that can be stored.

Test

Perform a calculation and open the browser’s Application/Storage tools.

Find:

calculator-history

Confirm that it contains the history array as JSON.

Clear the history and confirm the stored value changes.

Checkpoint

Calculator history is now written to browser storage whenever it changes.