Advertisement
otkalce

State persistence - localStorage

Mar 21st, 2023
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.33 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta charset="utf-8" />
  5.     <title>Localstorage example</title>
  6. </head>
  7. <body onload="testLocalStorage()">
  8.     <script>
  9.         function testLocalStorage() {
  10.             let rv1 = localStorage.getItem("receiptValue");
  11.             console.log(rv1); // Will print null, there's no value for this key
  12.  
  13.             // Set value for the key
  14.             localStorage.setItem("receiptValue", 100);
  15.  
  16.             let rv2 = localStorage.getItem("receiptValue");
  17.             console.log(rv2); // Will print value
  18.  
  19.             // Clear the storage
  20.             localStorage.clear();
  21.  
  22.             let rv3 = localStorage.getItem("receiptValue");
  23.             console.log(rv3); // Will print null, storage is empty
  24.  
  25.             // To set the complex value, use JSON serialization
  26.             let complexValue = {
  27.                 a: 1,
  28.                 b: "Some text",
  29.                 c: [100, 200, 300],
  30.                 d: {
  31.                     hello: "world"
  32.                 }
  33.             }
  34.             let serialized = JSON.stringify(complexValue); // serialize
  35.             localStorage.setItem("complexData", serialized);
  36.  
  37.             let deserialized = JSON.parse(localStorage.getItem("complexData")); // deserialize
  38.             console.log(deserialized);
  39.         }
  40.     </script>
  41. </body>
  42. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement