Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why localStorage.getItem always return string?

It's weird. I find localstorage.getItem's type in lib.dom.d.ts returns 'string | null', but when I use it in my app it always return string Why?

like image 789
JiWeiZhao Avatar asked Sep 09 '19 05:09

JiWeiZhao


People also ask

Is localStorage value always a string?

Description. The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings. localStorage data is specific to the protocol of the document.

What does localStorage getItem return?

The getItem() method of the Storage interface, when passed a key name, will return that key's value, or null if the key does not exist, in the given Storage object.

What is the return type of getItem ()?

The GetItem operation returns a set of attributes for the item with the given primary key. If there is no matching item, GetItem does not return any data and there will be no Item element in the response.

What does localStorage getItem return if not found?

The localStorage API uses the getItem method to retrieve data. The method takes a single argument that is the key to the data. If the data is not found, the method returns null .


2 Answers

Because that is how it is:

The keys and the values are always strings

See the doc: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

like image 53
François Huppé Avatar answered Oct 11 '22 04:10

François Huppé


If you use json object in the localStorage then you can use JSON.stringify() and JSON.parse() method .

To store object in localStorage ,

localStorage.setItem('token', JSON.stringify(user)); 

To get object from localStorage ,

user = JSON.parse(localStorage.getItem('user'));

Here , you will get the object rather than string .

like image 34
Pushprajsinh Chudasama Avatar answered Oct 11 '22 06:10

Pushprajsinh Chudasama