Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {});

I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign the type so that I can use it like:

JSON.parse(savedHistory).id

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Presentation - hyperlink only functioning for final slide

I have a question about Lean Slider, which you can check out at My goal is to link each slide to a different URL. However, I'm facing an issue where only the code in the last slide seems to be executed and applied to all other slides. For example, if ...

Save the value of a webpage element into a variable and utilize it across multiple JavaScript files in TestCafe

We are working in the insurance domain and have a specific scenario that we want to achieve using TestCafe: 1st step: Login into the application 2nd step: Create a claim and store the claim number in a global variable 3rd step: Use the globally declared c ...

Problem encountered with AngularJS html5mode URL functionality

I am encountering an issue with my AngularJS application that does not contain any nodeJS code. The problem lies in removing the # from the URL and I have implemented ui-routes for routing. 'use strict'; var app = angular.module('myapp&apos ...

Even after refreshing the page, Chrome stubbornly insists on showing the old data

I've been working on a single-page application where one page triggers server requests every time it loads. After making changes and deploying them, I noticed that the live version of the application was not reflecting the updates. Even though the cha ...

Changes are being made to the state, but the updates are not showing up in the user interface of my photo feed

Welcome everyone, I'm currently immersed in learning react and have developed several apps using react, such as a hotel website (using react and contentful cms), an e-commerce website (using react, contentful cms, paypal), githubfinder app, todos app, ...

Retrieving the <html> tag within an Angular component

In an Angular component, the <body> and <head> tags can be accessed by injecting DOCUMENT as shown below: import { DOCUMENT } from '@angular/common'; import { Inject } from '@angular/core'; export class TestComponent { c ...

The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source. The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload. I have confirmed ...

Tips on displaying the appropriate object value in a text field based on the selection from a dropdown menu

In my Ruby on Rails form, I have a dropdown menu with various category names: <td> <div class="div1"> <%= f.collection_select(:category_id, Category.all, :name, id: 'category_select', :include_blank => & ...

What steps should I take to troubleshoot this Angular issue within a Visual Studio 2022 project that utilizes the Standalone Angular template?

After going through this tutorial and meticulously following each step, I encountered an error when trying to run the application: https://i.sstatic.net/EvYgg.jpg Can anyone advise on how to resolve this issue? I'm facing a similar error while attem ...

Session is not functioning properly as anticipated

import * as express from 'express'; import * as session from 'express-session'; import * as bodyParser from 'body-parser'; const app: express.Express = express(); app.use(bodyParser.json()); app.use(session({ secret: &apos ...

Trouble generating document with Firebase setDoc()

In my current project, I am successfully creating a new user with authentication and then using the generated UID to create a new document. Here is the code snippet: const currentUser = await auth.createUserWithEmailAndPassword(email, pass); consol ...

`req.user` seems to be unresolved, but it is actually defined

Currently, I am working on developing an Express.js application that utilizes Passport.js for authentication in an administration panel. The program is functioning correctly at the moment, with my app.js initializing passport and setting up sessions proper ...

Creating a water vessel design using CSS

Despite going through the JS tutorial, I still struggle with it and need some assistance. I believe using a jsfiddle would be helpful. I am attempting to use JS to create a small box that changes color from green to empty based on the fullness of a "wate ...

Display or conceal a div element depending on the user's choice

I am looking to hide inactive divs, but whenever I reload the page, all tab contents merge into one. The screenshot below shows the issue I'm facing. Screenshot Below is the code snippet: $('.tab a').on('click', function ...

Swap the < symbol with &gt; and & with &amp; within a specific node or location in an XML document

Hello everyone, I have a XML file with a node named Section, where certain characters like & and < are treated as invalid. I need to replace < with &lt; and & with &amp; only within the Section Node. Currently, I am using the following Java ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Unable to reinitialize the DataTable using Angular Datatable

I've been working on an Angular application that has a simple CRUD functionality. Initially, I tested my data with a static HTML table and everything was functioning as expected. However, I decided to implement a data table framework called Angular da ...

Tips for expanding the content of a blogger page to fill the entire frame of the page

Check out this page: . Currently, the video on the page does not fill up the entire screen. Any suggestions for a solution? ...

TypeDI is failing to recognize Services from a nearby external package

I've encountered an issue with my mono repo project that contains two packages built using Lerna: Base and Libs. I'm attempting to utilize TypeDi dependency injection, but the classes marked with the Service() decorator from the Libs package are ...

Modifying a variable within the return statement in a React Native component

I am relatively new to React and React-native and I am facing challenges in understanding how to update a variable within the return method. Here is my current code snippet: import React, { Component } from "react"; import { View, StyleSheet, Platform, T ...