All kidding aside 😅, sometimes you need a place to save your website's data. A place where user choices, website configurations can sit, even if you refresh your page, or reopen your browser. .localStorage
is a good place for this use-case.
.localStorage
is a storage of key-value pairs linked to a site through its URL. Its API is pretty straightforward.
window.localStorage.setItem("myData", "2");
// ^ Its .setItem() accepts two parameters: key, value. We can drop the window. prefix.
localStorage.getItem("myData");
// ^ returns "2"
You can inspect the storage in Chrome's Application tab under the Local Storage item.
We can store non-primitive data types in .localStorage
as well. Let's say we would put an object there.
localStorage
.setItem("userData", { name: "David", surName: "Programmer"});
localStorage.getItem("userData");
// it's returning "[object Object]"
Why is the previous code snippet returning our object upon calling .getItem("userData")
? Because the .localStorage
stringifies the value given to it before saving it. The default conversion from an object to string is "[object Object]"
. That means that in order to preserve the true content of our data, we need to convert it before saving to the storage.
The preferred way is to use JSON.stringify()
and JSON.parse()
which functions stringify and de-stringify their inputs.
const data = { name: "David", surName: "Programmer" };
const stringifiedData = JSON.stringify(data);
localStorage.setItem("userData", stringifiedData);
JSON.parse(localStorage.getItem("userData"));
// it's returning now our original object
// {name: "David", surName: "Programmer"}
localStorage
can store up from 5 MB up to 10MB of data depending on your browser for a given domain. It is not accessible on the server, only the client's browser. It can come in handy for saving persisting data on your website.
Top comments (0)