1

Possible Duplicate:
HTML5 localStorage: check if item isset

I am developing an Sencha Touch 2 App using the localStorage.

I get values from the local storage like this:

var localStore = Ext.getStore('localStore');
localStore.getAt(0).data.name1 //get the value for key 'name1'

But on the first access the local storage is empty. How can I check if the key exists? When I do:

if(localStore.data.name1 === null)

I get:

Uncaught TypeError: Cannot read property 'name1' of undefined 
Community
  • 1
  • 1
Nico
  • 1,071
  • 1
  • 23
  • 39
  • Really ? http://www.bennadel.com/blog/2105-Exploring-HTML5-s-localStorage-Persistent-Client-Side-Key-Value-Pairs.htm – Titouan de Bailleul Oct 23 '12 at 16:53
  • I think there is a difference because I want to use the functions of sencha touch, not the native javascript functions... – Nico Oct 23 '12 at 21:09
  • Anyway, the problem here is that you do two different things. In the first case (localStore.getAt(0).data.name1), you're accessing the data of the first record of the store and then the 'name1' propertie of this record which makes sense. But then (localStore.data.name1) you're trying to access directly the data of the store and this property doesn't exist. Therefore localStore.data.name1 returns undefined. – Titouan de Bailleul Oct 23 '12 at 22:04

1 Answers1

0

See this jsFiddle example. localStore.getItem(name). Note getItem is a function.

var obj = {foo: 'bar'};

// set
localStorage.setItem('testObject', JSON.stringify(obj));

// get
var get = localStorage.getItem('testObject');

console.log(JSON.parse(get));

​ ​

krg
  • 2,650
  • 2
  • 12
  • 9
  • 1
    When I try this, I always get a null value. And what is localStorage? my localStore is an sencha touch local storage proxy and has no method getItem: Uncaught TypeError: Object [object Object] has no method 'getItem' – Nico Oct 23 '12 at 14:43
  • Ah, I see. I think I misunderstood the problem. So only on first attempt is it undefined. If so, I would try if (typeof localStorage.getItem === 'function') to see if it's defined before using it. – krg Oct 23 '12 at 14:53
  • Thanks for your help, I found out that if no data exists localStore.data.length is 0 and >0 if data exist. I think I will use that... – Nico Oct 23 '12 at 15:09