1

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);
 }
  • Does this answer your question? [How to store objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage) – Ronnie Royston Jun 16 '22 at 19:08
  • During `getValue` you're not actually doing anything with the result. You either want to `return localStorage.getItem(key)` it or assign it to a property of `UI` to be accessed by your app. As @kunuos pointed out, you can make both methods `static` methods if `UI` is simply a utility to be used by other modules, and additionally that you probably want to stringify values before saving them. – Sam Jun 16 '22 at 19:15
  • thanks a lot right I'm not returning the value that cases me undefined instead – ahmed hussin Jun 16 '22 at 19:24
  • please another question, when I'm retrieving data using getValue() and binding its value variable in the constructor method inside the class it returns an empty array however there are data in local storage, please take a look at the link below. https://jsfiddle.net/cj3s69xa/ – ahmed hussin Jun 16 '22 at 21:53

1 Answers1

1

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.

kanuos
  • 985
  • 9
  • 16