Skip to content

localStorage & JSON

localStorage ให้เก็บข้อมูลใน browser ที่คงอยู่แม้ปิดแล้วเปิดใหม่ — เหมาะสำหรับ user preferences, drafts, simple app state

const user = { name: "สมชาย", age: 28, skills: ["JS", "React"] };
// Object → JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"สมชาย","age":28,"skills":["JS","React"]}'
// JSON string → Object
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // "สมชาย"
// pretty print (indent 2 spaces)
console.log(JSON.stringify(user, null, 2));
// เก็บค่า (รับ string เท่านั้น)
localStorage.setItem("theme", "dark");
localStorage.setItem("lang", "th");
// อ่านค่า
const theme = localStorage.getItem("theme"); // "dark"
// ลบ key
localStorage.removeItem("theme");
// ลบทั้งหมด
localStorage.clear();
// เช็คจำนวน keys
console.log(localStorage.length);
// เก็บ object — ต้อง stringify ก่อน
const settings = { theme: "dark", fontSize: 16, lang: "th" };
localStorage.setItem("settings", JSON.stringify(settings));
// อ่านกลับ — ต้อง parse
const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.theme); // "dark"
// safe save
function saveToStorage(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (error) {
console.error("Storage save failed:", error.message);
return false;
}
}
// safe load with default
function loadFromStorage(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
console.error("Storage load failed:", error.message);
return defaultValue;
}
}
// ใช้งาน
saveToStorage("todos", [{ text: "ซื้อของ", done: false }]);
const todos = loadFromStorage("todos", []);

ข้อจำกัดของ localStorage

Section titled “ข้อจำกัดของ localStorage”
ข้อจำกัดรายละเอียด
ขนาด~5-10 MB ต่อ origin
ชนิดข้อมูลstring เท่านั้น (ต้อง stringify)
Scopeต่อ origin (domain + port)
Syncsynchronous — block main thread
Securityไม่ควรเก็บ sensitive data (passwords, tokens)
// sessionStorage — เหมือน localStorage แต่หายเมื่อปิด tab
sessionStorage.setItem("temp", "ค่าชั่วคราว");
const temp = sessionStorage.getItem("temp");
// ปิด tab → หายไป

เมื่อไหร่ควรใช้อะไร?

Section titled “เมื่อไหร่ควรใช้อะไร?”
Use Caseเลือก
User preferences (theme, lang)localStorage
Shopping cartlocalStorage
Form draftsessionStorage
Auth tokenshttpOnly cookie
Large dataIndexedDB