It's unfortunate that localStorage.getItem
only returns a string or null, making it challenging to inject the correct type after JSON parsing without a type cast/assertion.
To address this limitation, I suggest creating a wrapper function for localStorage.getItem
that handles the parsing and type conversion:
const getHistory = () => {
const json = localStorage.getItem('x') ?? '{}';
return JSON.parse(json) as { id?: number };
// Modify the number type as needed
};
// ...
// Fetch initial history once instead of on every render:
const initialHistory = getHistory();
const App = () => {
const [history, setHistory] = useState(initialHistory);
By using this method, the history
variable will hold a typed object rather than a string, which is more convenient for manipulation.