ahmed hussin
ahmed hussin

Reputation: 23

How to retrieve data from local storage in javascript

i have a class called ui and after saving data in local storage using save method it works but when i'm getting the data with loadData method it gives me undefined .. i want to know why ?!!

class UI{ 

 save(key, value) {
  localStorage.setItem(key, value);
 }

 getValue(key) {
  localStorage.getItem(key);
 }

Upvotes: 1

Views: 1945

Answers (1)

kanuos
kanuos

Reputation: 1213

You didn't mention what's the value you are saving to the localStorage. If it's not a primitive data type, you'd need to convert the value into a string before you save it in the localStorage using the JSON.stringify(value) method and when you run getvalue you'd want to parse the stringified value using JSON.parse(localStorage.getItem(key)).

PS: using static methods make sense when you are trying to save or retrieve data to/from the localStorage. Giving access to individual objects to have access to localStorage might cause problems in the future.

Upvotes: 1

Related Questions