When working with Local Storage in web development, it’s crucial to understand how data is stored and retrieved. Local Storage is a great tool for saving small amounts of data in the browser, but it only stores data in a specific format—JSON (JavaScript Object Notation).
Why JSON Matters
JavaScript objects, which developers frequently work with, can’t be directly stored in Local Storage. Instead, these objects need to be converted to JSON strings before saving. Similarly, when retrieving data from Local Storage, you’ll need to convert the JSON string back into a JavaScript object to make it usable.
How to Save and Retrieve Data
Here’s a simple breakdown of the process:
- Saving a JavaScript object:
- First, you need to convert the object to a JSON string using
JSON.stringify()
.
const user = {
name: “Marie”
};
const userToJSON = JSON.stringify(user); // Convert object to JSON
- Then, store it in Local Storage.
let user = { name: “Kevin”, age: 30 };
localStorage.setItem(“user”, JSON.stringify(user));
- Retrieving the data:
- When you retrieve the data, it will come back as a JSON string. Use
JSON.parse()
to convert it back into a JavaScript object.
let storedUser = JSON.parse(localStorage.getItem(“user”));
console.log(storedUser.name); // Outputs: Kevin
Key Takeaways
- Local Storage stores data as strings in JSON format.
- Always use
JSON.stringify()
to convert objects to strings before saving. - Use
JSON.parse()
to convert JSON strings back into usable JavaScript objects.
Discover more from Kvnbbg.fr
Subscribe to get the latest posts sent to your email.