Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor button onclick trigger all Lifecycle method again

Tags:

blazor

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

like image 795
Karl Christian Gutierrez Abant Avatar asked Sep 14 '26 13:09

Karl Christian Gutierrez Abant


1 Answers

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.

like image 199
Jesse Good Avatar answered Sep 17 '26 15:09

Jesse Good



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!