CodingNic

LocalStorage Persistence

Create Task Save and Load Functions

LocalStorage Persistence 10 min read

Create Task Save and Load Functions

Create Task Save and Load Functions

Create one place for saving tasks and one place for loading them.

1. Choose a storage key

javascript
const STORAGE_KEY = "my-todo-list";

2. Save the task array

javascript
function saveTasks() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

3. Load saved tasks

Use a small loader that falls back to an empty array when nothing has been saved yet:

javascript
function loadTasks() {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY));
    return Array.isArray(saved) ? saved : [];
  } catch (error) {
    return [];
  }
}

4. Initialize the task data

Instead of always starting with [], initialize your task data from loadTasks().

Checkpoint: Existing saved tasks are available when the application starts, while a first-time visit starts with an empty task list.