Tutorial hero
Lesson icon

Can't Load Record from a Sencha Touch Store?

Originally published February 13, 2014 Time 3 mins

More often than not, if you’re having trouble retrieving records from a store and receiving null or undefined values it is because the store was simply not loaded when the call was made. Now, you may have loaded the store before trying to retrieve the record but that does not necessarily mean the store has finished loading into memory. This is something that trips a lot of people up, so I thought it would be fitting to create a blog post about it.

The reason this happens is because the store load is asynchronous this means that it will run in parallel to your code, the rest of your code will not wait for the load to finish before continuing. To give an analogy it would be like asking your friend to go pick up some steaks for dinner so you could cook them, you’re not going to stand still doing nothing until he gets back (that would be a waste), but if you try to cook the steak before your friend gets back you’re going to have problems because you don’t have the steak yet.

Let me give you an example of how this might look:

//Create a reference to the store
var myStore = Ext.getStore('MyStore');

//Load the store
myStore.load();

//Store loading ...
//Store loading ...

//Retrieve a record from the store
console.log(myStore.getAt(0)); //This will not work

//Store loading ...
//Store loaded!

I’ve indicated the current status of the store in the comments, as you can see we’re trying to retrieve a record before the store has finished loading. This all happens in a matter of seconds, so if you were to inspect the store afterwards it would seem as though everything is loaded in fine and leave you wondering why a seemingly simple operation didn’t work.

Here’s how you can fix it

So what we want to do is wait for our friend to get back before we try to cook the steak, or, we want to tell a portion of our code to only execute once the store has finished loading. To do this, we can add a load listener to the store, and specify the code we want to execute inside of that:

myStore.on('load', function (s, rs) {
  //This code will be executed only once
  //the store is loaded
  console.log(myStore.getAt(0));
});

This is one of those things that can be really frustrating where it seems like your code should work but it just doesn’t, keep this in mind though and you should be fine!

Learn to build modern Angular apps with my course