C
C#2mo ago
DaClownie

✅ OnParametersSetAsync() in a blazor component being called before clicking a button in Blazor app

I created a component in Blazor, a CourseList which has a Parameter of TermId its added to the Terms.razor page as such
<button class="btn btn-primary" onClick="@(() => ShowCourses(term.Id))">Show Course List</button>

<CourseList TermId="termId" />

@code
Guid termId;

private void ShowCourses(Guid id)
{
if (termId == id)
{
return;
}
termId = id;
StateHasChanged();
}
<button class="btn btn-primary" onClick="@(() => ShowCourses(term.Id))">Show Course List</button>

<CourseList TermId="termId" />

@code
Guid termId;

private void ShowCourses(Guid id)
{
if (termId == id)
{
return;
}
termId = id;
StateHasChanged();
}
termId is a Guid that is only being assigned a value when one of the buttons next to the rendered terms is clicked. The CourseList component itself only displays if a bool showDetails is set to true. However, when the page is loaded, it automatically displays the table headers and tries to load the list of Courses that are within that if (showDetails) CourseList.razor:
@if (showDetails)
{
table code here ...
}

@code
[Parameter]
public Guid TermId { get; set; }
bool showDetails = false;

protected override async Task OnParameterSetAsync()
{
var result = await Http.GetAsync($"api/course/ListByTermId/{TermId}");
if (result.IsSuccessStatusCode)
{
courses = await result.Content.ReadFromJsonAsync<List<CourseResponse>>();
showDetails = true;
}
else
{
showDetails = false;
}
}
@if (showDetails)
{
table code here ...
}

@code
[Parameter]
public Guid TermId { get; set; }
bool showDetails = false;

protected override async Task OnParameterSetAsync()
{
var result = await Http.GetAsync($"api/course/ListByTermId/{TermId}");
if (result.IsSuccessStatusCode)
{
courses = await result.Content.ReadFromJsonAsync<List<CourseResponse>>();
showDetails = true;
}
else
{
showDetails = false;
}
}
Why is this OnParameterSetAsync() being called on page load before clicking a button?
1 Reply
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server