localStorage & JSON
localStorage & JSON
Section titled “localStorage & JSON”localStorage ให้เก็บข้อมูลใน browser ที่คงอยู่แม้ปิดแล้วเปิดใหม่ — เหมาะสำหรับ user preferences, drafts, simple app state
JSON.stringify & JSON.parse
Section titled “JSON.stringify & JSON.parse”const user = { name: "สมชาย", age: 28, skills: ["JS", "React"] };
// Object → JSON stringconst jsonString = JSON.stringify(user);console.log(jsonString);// '{"name":"สมชาย","age":28,"skills":["JS","React"]}'
// JSON string → Objectconst parsed = JSON.parse(jsonString);console.log(parsed.name); // "สมชาย"
// pretty print (indent 2 spaces)console.log(JSON.stringify(user, null, 2));import jsonjson_string = json.dumps(user, ensure_ascii=False)parsed = json.loads(json_string)// C ใช้ library เช่น cJSONcJSON *json = cJSON_CreateObject();cJSON_AddStringToObject(json, "name", "สมชาย");char *str = cJSON_Print(json);-- PostgreSQL มี JSON typeSELECT '{"name": "สมชาย"}'::jsonb -> 'name';-- หรือ JSON functionsSELECT jsonb_build_object('name', 'สมชาย', 'age', 28);localStorage API
Section titled “localStorage API”// เก็บค่า (รับ string เท่านั้น)localStorage.setItem("theme", "dark");localStorage.setItem("lang", "th");
// อ่านค่าconst theme = localStorage.getItem("theme"); // "dark"
// ลบ keylocalStorage.removeItem("theme");
// ลบทั้งหมดlocalStorage.clear();
// เช็คจำนวน keysconsole.log(localStorage.length);เก็บ Object / Array
Section titled “เก็บ Object / Array”// เก็บ object — ต้อง stringify ก่อนconst settings = { theme: "dark", fontSize: 16, lang: "th" };localStorage.setItem("settings", JSON.stringify(settings));
// อ่านกลับ — ต้อง parseconst saved = JSON.parse(localStorage.getItem("settings"));console.log(saved.theme); // "dark"Helper Functions
Section titled “Helper Functions”// safe savefunction 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 defaultfunction 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) |
| Sync | synchronous — block main thread |
| Security | ไม่ควรเก็บ sensitive data (passwords, tokens) |
sessionStorage
Section titled “sessionStorage”// sessionStorage — เหมือน localStorage แต่หายเมื่อปิด tabsessionStorage.setItem("temp", "ค่าชั่วคราว");const temp = sessionStorage.getItem("temp");// ปิด tab → หายไปเมื่อไหร่ควรใช้อะไร?
Section titled “เมื่อไหร่ควรใช้อะไร?”| Use Case | เลือก |
|---|---|
| User preferences (theme, lang) | localStorage |
| Shopping cart | localStorage |
| Form draft | sessionStorage |
| Auth tokens | httpOnly cookie |
| Large data | IndexedDB |