Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Last active December 20, 2022 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpowell4/f2575ea47f3b70c0014bc17aa9b08501 to your computer and use it in GitHub Desktop.
Save danielpowell4/f2575ea47f3b70c0014bc17aa9b08501 to your computer and use it in GitHub Desktop.
react component to read and display localStorage in a _more_ human readable manner
import * as React from "react";
import { SmallButton } from "../../shared"; // a cool <button />
const DisplayLocalStorage = () => {
const [changes, setChanges] = React.useState(0); // triggers re-renders
let localStorageState = {};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
let value;
try {
value = JSON.parse(localStorage.getItem(key));
} catch (_error) {
value = localStorage.getItem(key);
}
localStorageState[key] = value;
}
const clearStorage = () => {
localStorage.clear();
setChanges(prev => prev + 1);
};
const clearItem = key => {
localStorage.removeItem(key);
setChanges(prev => prev + 1);
};
return (
<div>
<header>
<h1 className="title">Device Storage Debugger</h1>
<p className="help-block">
This page is intended for use when corresponding with the support
desk.
</p>
<p className="help-block">
You have made {changes} changes.{" "}
<SmallButton extraClassName="primary" onClick={clearStorage}>
Clear Storage
</SmallButton>
</p>
</header>
{Object.keys(localStorageState)
.sort()
.map(key => (
<React.Fragment key={key}>
<details>
<summary>
{key}{" "}
<SmallButton
extraClassName="primary"
onClick={() => clearItem(key)}
>
Clear Item
</SmallButton>
</summary>
<pre>{JSON.stringify(localStorageState[key], null, 2)}</pre>
</details>
<hr />
</React.Fragment>
))}
</div>
);
};
export default DisplayLocalStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment