Unlisted
Edited
Oct 5, 2024
Insert cell
Insert cell
original_data = ({
name: "Sample Project",
description: "Initial project data",
status: "active"
})
Insert cell
// Make changes to the data -- run this manually, as it may reset on page load.
original_data.status = "completed"
Insert cell
// Verify change; re-run this after page load to ensure changes took effect
original_data
Insert cell
///Save the changed data to browser's localStorage
localStorage.setItem('ephemeral_data', JSON.stringify(original_data));
Insert cell
// Retrieve the data from localStorage
ephemeral_data_check = JSON.parse(localStorage.getItem('ephemeral_data'));
Insert cell
// Make changes to the data using a delay to ensure it's correctly overwritten.
{// Simulate asynchronous data loading
async function loadOriginalData() {
// Simulate delay (e.g., API call or data fetch)
return new Promise((resolve) => {
setTimeout(() => {
// load original data
resolve(original_data);
}, 1000); // Simulating a 1-second delay
});
}

// Await data loading and update it
async function processAndStoreData() {
// Step 1: Await the loading of the original data
let original_data = await loadOriginalData();
return("Original Data Loaded:", original_data);

// Step 2: Make changes to the data
original_data.status = "completed"; // Update the status
// Step 3: Save the updated data to localStorage
localStorage.setItem('eph_data', JSON.stringify(original_data));
return("Updated Data Saved to localStorage.");
}

// Call the function to load, modify, and store the data
processAndStoreData();
return original_data
}
Insert cell
// Check the data in LocalStorage
{// Create an empty object
let localStorageData = {};

// Check if localStorage has any data
if (localStorage.length > 0) {
console.log("Listing all data in localStorage with keys as object property names:");
// Loop through each key
for (let i = 0; i < localStorage.length; i++) {
// Get the key at this index
let key = localStorage.key(i);
// Get the value associated with the key
let value = localStorage.getItem(key);
// Try to parse the value as JSON if it's a valid JSON string
try {
value = JSON.parse(value); // Convert JSON string to an object if possible
} catch (e) {
// If it's not JSON, leave it as a string
}
// Assign the key as the property name in the object, and the value as its value
localStorageData[key] = value;
}

// Log the full object with keys as property names
return(localStorageData);
} else {
return("No data found in localStorage.");
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more