'Is there a way to rerun OnInitializedAsync when a variable is changed in Blazor WASM?
I understand OnInitializedAsync is running once before the component is loaded. However, I am passing in a variable to the API and I would like to have it rerender the UI once the variable is changed. I am just not sure what the best way to go about it is.
@page "/"
@inject HttpClient Http
<h1>Pokemon</h1>
<p></p>
@if (pokemons == null)
{
<p><em>Loading...</em></p>
}
else
{
@foreach (var n in pokemons.results)
{
<div class="card" style="width: 18rem;">
<img [email protected] class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">@n.name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
}
@pokemons.count
<br />
@offset
<nav aria-label="Page navigation example">
<ul class="pagination">
@for (int b = 0; b < pokemons.count; b += 20)
{
int local_b = b;
<li class="page-item"><button class="page-link" @onclick="() => Paginate(local_b)">@b</button></li>
}
</ul>
</nav>
}
@code {
private PokemonList pokemons;
private PokemonDetail pokemonDetails;
private int limit = 20;
private int offset = 0;
public void Paginate(int value)
{
Console.WriteLine(value);
this.offset = value;
InvokeAsync(StateHasChanged);
}
protected override async Task OnInitializedAsync()
{
pokemons = await Http.GetFromJsonAsync<PokemonList>($"https://pokeapi.co/api/v2/pokemon/?offset={offset}&limit={limit}");
foreach (var p in pokemons.results)
{
pokemonDetails = await Http.GetFromJsonAsync<PokemonDetail>(p.url);
p.url = pokemonDetails.sprites.front_default;
}
}
public class PokemonList
{
public int count { get; set; }
public string next { get; set; }
public List<Pokemon> results { get; set; }
}
public class Pokemon
{
public string name { get; set; }
public string url { get; set; }
}
public class PokemonDetail
{
public PokemonSprites sprites { get; set; }
}
public class PokemonSprites
{
public string front_default { get; set; }
}
}
Solution 1:[1]
You can have a function for your API call and can call this function whenever you want
private async Task FetchPokemonList()
{
pokemons = await Http.GetFromJsonAsync<PokemonList>($"https://pokeapi.co/api/v2/pokemon/?offset={offset}&limit={limit}");
foreach (var p in pokemons.results)
{
pokemonDetails = await Http.GetFromJsonAsync<PokemonDetail>(p.url);
p.url = pokemonDetails.sprites.front_default;
}
}
And can call FetchPokemonList in OnInitializedAsync
protected override async Task OnInitializedAsync()
{
await FetchPokemonList();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Surinder Singh |
