Issue
Pretty simple question that I already have a solution for but it looks ugly to me.
I am trying to access local storage but I need to useEffect and if I want to extract the value from inside useEffect I need to instantiate before the codeblock in the higher scope.
Typescript does not accept var temp:JSON = {}
So I have to do the cumbersome var temp:JSON = JSON.parse(JSON.stringify({}))
which works. But it seems somewhat stupid to me that Javascript will randomly coerce my string into truthy values with == but can't coerce an empty Object into JSON.
Solution
JSON
type is probably not what you need to be using for this. This type reflects an interface for converting data to/from JSON, aka the JSON global object in JavaScript.
Instead, you should create an interface that reflects the type of data stored in localstorage, then use that interface as the type for the parsed string from localstorage:
interface StoredObject {
name?: string;
kind?: string;
...
}
...
const [storedObject, setStoredObject] = useState<StoredObject>();
useEffect(() => {
const jsonString = localStorage.getItem(key);
setStoredObject(JSON.parse(jsonString));
}, []);
Answered By - smac89
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.