What is the appropriate pattern for requesting external data?

Hello,

I have an application that uses some external data (currently a JSON file but in the future a REST API) that is later shown in a ion-list. I was following the examples shown where I request the data in the constructor of the Page will will return a Promise that resolves when the data is available.

The problem is that the transition to that page gets delayed until the data is loaded which makes the application feel laggy. I would expect that the transition happens immediately and then once the data is available the list is populated but this does not seem to be the case.

What is the recommendation for this case?

Thanks!

  • Oscar.

If you get many data --> you can use the ionView hooks of ionic. so you can load the data in your component, but show them only, if the transition has finished.

So you can use “ionViewDidEnter” and you can be sure that the transition animation has finished.

Which even would you use to request the data? ionViewDidEnter? My issue is that requesting it in the constructor causes the application to be laggy, so I want to know the best practice for it.

Do not request it in the constructor. Request for the data in “ionViewDidEnter”. That way the you are sure the page has already loaded before it starts to request for the data

1 Like

constructor should be synchronous and not for doing async and heavy work.

so you can start your request in the willEnter hook, (because this is a background-request and blocks nothing). But do not show results --> put a ngIf at your dom like --> <div *ngIf="viewEntered">YOUR LIST HERE<div>

And in the DidEnter Hook you set the flag to true, so if there are results, the browsers renders them.

2 Likes

Thank you for your help. Maybe recommendation should be added to the docs since every case where data is requested I’ve seen it done in the constructor. Thanks!