LocalStorage Persistence
10 min read
Handle Stored Task Data Safely
Handle Stored Task Data Safely
Stored data can be missing, invalid, or from an older version of the application. Keep the loader defensive.
Validate the basic task fields before using them:
function normalizeTask(task, index) {
return {
id: task.id ?? index + 1,
title: String(task.title || "Untitled task").trim(),
due: /^\d{4}-\d{2}-\d{2}$/.test(task.due || "") ? task.due : "",
priority: ["High", "Medium", "Low"].includes(task.priority)
? task.priority
: "Medium",
completed: Boolean(task.completed)
};
}
Use it when the stored value is an array:
return saved.map(normalizeTask);
If parsing fails or the stored value is not an array, return an empty array or your chosen starter data.
Checkpoint: Corrupt or unexpected stored values do not stop the application from loading.