Get data from storage before page is load

Hi, how can i get data from local storage before page is loaded?

If you are using Angular, take a look at Routeguards as a possible solution

my problem is that I want to get data from my local storage before the page is load so I can save that values inside page var so I could make things faster without waiting storage to respond.

Storage should only be used for communicating across app runs, which means that you only want to be reading from it once, generally at app startup, which will also get you the "fast"est response possible. I also recommend never interacting directly with Storage in pages: do so only in services. The service can expose the data that is coming from Storage as a future (Promise or Observable), pages do whatever they need to when that future resolves.

@ChrisGriiffith’s suggestion of route guards may indeed make sense if you absolutely have to block until complicated pipelines have everything they need, but if you are talking about “make things faster”, I get the sense that’s not your primary concern here. There is nothing you can do about how long Storage takes to return a particular value; so your app code can’t actually make anything faster; all it can do is to affect the perception of responsiveness, and in this case I would think route guards would actually make things worse.

Let’s say it takes a second for Storage to return a value you want to display in a page. That retrieval starts when the app is started, and the page in question is the very first page the user sees. If you block navigation with a route guard, the user sees the app as frozen for that one second. If you follow the “load from Storage at service startup, expose as future, do something that triggers Angular change detection when future resolves” pattern, your page is free to use that second to give some indicator to the user that things are happening (pop a loading spinner, use placeholder data, etc), which will make the app feel as responsive as possible.

1 Like