Blazor OnInitializedAsync

ICodeInTx 56 Reputation points
2021-01-17T22:18:56.927+00:00

Is there a fix to OnInitializedAsync being called twice in Blazor server project? I've seen people say get the results from the database and store them in cache so the 2nd call will be from cache. This isn't a fix and is a terrible answer and surely not a solution. Is there a method like OnInitializedAsync that is only called once where we can call our API's to get the data for the screen?

Scott

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,375 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,061 Reputation points
    2021-01-18T02:59:03.68+00:00

    Hi @ScottDurrett-9763 ,

    You could go to _Host.cshtml and change render-mode="ServerPrerendered" to render-mode="Server", and it would be called only once.

    Reference:


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Rena

    4 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. KalyanChanumolu-MSFT 8,316 Reputation points
    2021-01-18T04:51:22.693+00:00

    Hello @ScottDurrett-9763 Thank you for reaching out.
    As pointed by @Rena Ni - MSFT , you are most probably using the ServerPrerendered mode.
    This is useful when you need to display the page immediately to the user and then make it interactive. Changing it to Server should fix the problem.

    If you need a method that is called only once, you can use OnAfterRenderAsync. This is invoked after the component has rendered.

            protected override async Task OnAfterRenderAsync(bool firstRender)  
            {  
                if (firstRender)  
                {  
                   await LoadData();  
                }  
            }  
    

    ----------

    If an answer is helpful, please "Accept answer" or "Up-Vote" for the same which might be beneficial to other community members reading this thread.

    4 people found this answer helpful.