Search code examples
mauimaui-community-toolkit

How to load data on page start in .net maui


How do you correctly start a data load in a page in a maui application? I see examples for how to bind existing data and how to start a call on pull down or button press but not how to start a call when the page first starts.


Solution

  • You can make the OnAppearing() override async and await any loading calls:

    protected override async void OnAppearing()
    {
        base.OnAppearing();
    
        await someViewModelOrApi.LoadDataAsync();
    }
    

    Note that this will load the data every time the page appears again.

    Alternatively, you can also use the Loaded event of the Page:

    public MyPage()
    {
        Loaded += OnPageLoaded;
    }
    
    private async void OnPageLoaded(object sender, EventArgs e)
    {
        await someViewModelOrApi.LoadDataAsync();
    }
    

    In another answer I've also described how you can load data when a Page and its ViewModel are instantiated.