Examples
JS LocalStorage CRUD
CRUD with localStorage
JavaScript localStorage CRUD manages data with JSON serialization.
Introduction to LocalStorage
The localStorage API is a web storage feature that allows you to store data in the browser with no expiration date. This data persists even after the browser is closed and reopened, making it a useful tool for maintaining state across sessions.
LocalStorage stores data as key-value pairs and is limited to approximately 5MB per origin. It is essential to note that all data stored in localStorage is stored as strings.
Understanding JSON Serialization
Since localStorage can only store strings, you need to serialize (convert) your data into a string format. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write. It is also easy for machines to parse and generate.
You can use JSON.stringify()
to convert JavaScript objects into a JSON string and JSON.parse()
to convert JSON strings back into JavaScript objects.
Create Operation
To add data to localStorage, use the setItem()
method. This method takes two arguments: the key and the value. When storing objects, ensure the value is serialized using JSON.stringify()
.
Read Operation
To retrieve data from localStorage, use the getItem()
method. If the data stored is an object, you will need to parse it back into an object using JSON.parse()
.
Update Operation
Updating an item in localStorage involves retrieving the item, modifying it, and then storing it back into localStorage. Use JSON.parse()
to modify the object and JSON.stringify()
to serialize it again.
Delete Operation
To remove an item from localStorage, use the removeItem()
method, passing the key as the argument.
Conclusion
JavaScript localStorage provides a simple way to perform CRUD operations directly in the browser. By using JSON serialization, you can store complex data structures like objects and arrays. This makes localStorage a powerful tool for managing application state on the client side.
Examples
- Form Validation
- Dynamic Lists
- AJAX Fetch
- LocalStorage CRUD
- Simple Animation
- Search Filter
- Toggle Visibility
- Previous
- AJAX Fetch
- Next
- Simple Animation