Blazor button onclick trigger all Lifecycle method again

I'm having a problem in my blazor app.

After onclick trigger in my button, i call function CheckSchedule

enter image description here

I sucessfully call the method but my problem is I think my page initialized again because the page call my all my lifecycle method again. The page run protected override async Task OnInitializedAsync() again.

enter image description here

protected override async Task OnInitializedAsync()
{
try
{
if (Branches == null)
{
Branches = await BranchService.GetBranches();
branchList = Branches.OrderBy(branch => branch.name).ToList();
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
}

can i know why this is happening? because it resets my list again which is should be not.

Update: Hi everyone, my problem solved by removing HTML form.

Thank you

Upvotes: 3

Views: 1338

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

Credits go to @enet for figuring out the issue.

Solution

In your screenshot, it appears that you have not set the type of button. Try adding type="button" as an attribute to your button and see if that solves the issue.

Reason why OnInitializedAsync is called when you click the button

When you do not specify the type of button, it defaults to type="submit". Now usually this isn't an issue, however if a button of type="submit" is inside of a <form>, it causes an http request to happen. This will cause your page to refresh and your component to be recreated.

Incidentally, why do you check if Branches == null in the init method ? Can it be otherwise.

Upvotes: 3

Related Questions