I am currently trying to change the value of a variable on a HTML page & noticed that the value bound to the page isn't getting updated on the page after it is already set synchronously.
Executing the first code results in "outputVal" being presented as "Value during loading", while the second example correctly displays "Final value".
@page "/example1"
<p>Output: @outputVal</p>
<button onclick="@ChangeOutputVal" width=1200px>Confirm</button>
@code {
private string outputVal = "Placeholder value";
private async void ChangeOutputVal() {
outputVal = "Value during loading";
await Task.Delay(100);
outputVal = "Final value";
}
}
@page "/example2"
<p>Output: @outputVal</p>
<button onclick="@ChangeOutputVal" width=1200px>Confirm</button>
@code {
private string outputVal = "Placeholder value";
private async void ChangeOutputVal() {
//outputVal = "Value during loading";
await Task.Delay(100);
outputVal = "Final value";
}
}
Am I doing something wrong or is this a bug? How do I update the page to display the correct value?
The main issue is that Maui Blazor just isn't going to update the outputVal
if it thinks its value hasn't changed. If you want to force UI to re-render the change for outputVal
after completing an asynchronous task in Maui Blazor, you can use StateHasChanged()
like below:
<p>Output: @outputVal</p>
<button @onclick="ChangeOutputVal" width=1200px>Confirm</button>
@code {
private string outputVal = "Placeholder value";
private async void ChangeOutputVal()
{
outputVal = "Value during loading";
await Task.Delay(100);
outputVal = "Final value";
StateHasChanged();
}
}