Load Data only the first time you enter a page

Hi guys,

in the forum i didn’t find this How-to so i am here to ask this.

Is there a way to fetch some data only the first time u enter in a specific page?

I have a linear navigation and i want to fetch some data when i swipe in the second page but only the first time. If a user swipe back (in page 1) and again swipe in page 2, the page 2 will not fetch again the data.

Hope someone can help :slight_smile:

Not sure if you’re using PageControl but doesn’t really matter what your using for your page, as long as you use WhileActive like so in the following simplified example:

<PageControl>
  <Page></Page>
  <Page>
    <WhileActive>
      <Callback Handler="{loadData}" />
    </WhileActive>
  </Page>
</PageControl>

var isDataLoaded = Observable(false);

function loadData() {
  if(!isDataLoaded) {
    fetch(url).then(function(res) {...}).then(data) {
     // do stuff with your data
     isDataLoaded.value = true; // set the isDataLoaded to true so that it won't load the data again
    });
  }
}

module.exports = {
  loadData: loadData
}

You could also check the isDataLoaded boolean through ux:

<PageControl>
  <Page></Page>
  <Page>
    <WhileActive>
      <WhileFalse Value="{isDataLoaded}>
        <Callback Handler="{loadData}" />
      </WhileFalse>
    </WhileActive>
  </Page>
</PageControl>

var isDataLoaded = Observable(false);

function loadData() {
  fetch(url).then(function(res) {...}).then(data) {
    // do stuff with your data
    isDataLoaded.value = true; // set the dataLoaded to true so that it won't load the data again
  });
}

module.exports = {
  isDataLoaded: isDataLoaded,
  loadData: loadData
}

hi edwin.

Yes this is exactly what i did. But is there a trigger to do that instead of define a boolean variable?

Nope, not that I know of

There is no trigger which only triggeres the first time an event is called. Since this case is quite specifig i think the approach you’ve used is a good one. If you absolutely want to keep this logic inside UX (which i don’t think is a good practice anyway), then you could do it by wrapping the callback in a WhileTrue.

Something like this:

<WhileTrue ux:Value="activateOnce">
    <Callback Handler="{loadData}" />
</WhileTrue>

...

<Page>
    <WhileActive>
        <Set activateOnce.Value="true" />
    </WhileActive>
</Page>