Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returns key and value of a localstorage object

I get a localstorage built like this:

  TYPE_MAPPING  : {"type":{"B2B":"B2B","UNKNOWN":"B2C","blabla":"B2C"}}

when I want to retrieve the key and value from localstorage

  const type = localStorage.getItem(TYPE_MAPPING);

  for (const [key, value] of Object.entries(type)) {
  console.log(`${key}: ${value}`);
   }

I get the following error message :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  TS2769: No overload matches this call.   
  Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike<string>): [string, string][]', gave the following error.     
  Argument of type 'string | null' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike<string>'.       
  Type 'null' is not assignable to type '{ [s: string]: string; } | ArrayLike<string>'.   Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.     
  Argument of type 'string | null' is not assignable to parameter of type '{}'.       Type 'null' is not assignable to type '{}'.

what would be the solution to recover the keys and values of the localStorage ?

>Solution :

**localstorage.getItem** return a string, so you have to parse it before
  const type = JSON.parse(localStorage.getItem(TYPE_MAPPING));

  for (const [key, value] of Object.entries(type)) {
  console.log(`${key}: ${value}`);
   }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading