Chapter 14. Data Persistence
We can animate and interact, stream, play, and render, but we always come back to the data. Data is the foundation on which we build the majority of our JavaScript applications. In the first part of the book we worked with the JavaScript languages standards for data types, in Chapter 13 we fetched data from a remote source, and in Chapter 20 weâll work with data on the server, manipulating data using APIs and data sources. Data and JavaScript, friends forever.
In this chapter, weâre going to look at ways we can persist data with JavaScript in the browser using cookies, sessionStorage
, localStorage
, and IndexedDB.
Persisting Information with Cookies
Problem
You need to read or set the value of a browser cookie.
Solution
Use document.cookie
to set and retrieve cookie values:
document
.
cookie
=
'author=Adam'
;
console
.
log
(
document
.
cookie
);
To encode strings, use encodeURIComponent
, which will remove any commas, semicolons, or whitespace:
const
book
=
encodeURIComponent
(
'JavaScript Cookbook'
);
document
.
cookie
=
`title=
${
book
}
`
;
console
.
log
(
document
.
cookie
);
// logs title=JavaScript%20Cookbook
Options can be added to the end of the cookie value and should be separated with a semicolon:
document
.
cookie
=
'user=Abigail; max-age=86400; path=/'
;
To delete a cookie, set an expiration date for the cookie that has already occurred:
function
eraseCookie
(
key
)
{
const
cookie
=
`
${
key
}
=;expires=Thu, 01 Jan 1970 00:00:00 UTC`
;
document
.
cookie
=
cookie
;
}
Get JavaScript Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.