Home > Enterprise >  Get quote from API not working on page load Blazor
Get quote from API not working on page load Blazor

Time:11-05

I want to get a Random Quote from an API I'm using, however it's not displaying the quote when the page loads, only after pressing a button, the function isnt binded to anything but works properly when i click the button for some reason. I tried to execute the method which loads the quote from an endpoint properly, but does not enter in the if(quote != null) only when i click the button.

`

@page "/"

@inject HttpClient Client
<PageTitle>Index</PageTitle>

<body>
<h3 >Breaking bad</h3>
<div  >
    <input type="text"   placeholder="Personaje" @bind="nombre" />
    <input type="button" @onclick="GetCharacter"  />

</div>


    @if (aratzfag == false){
        @GetRandomQuote();
        @if(quote != null){
      <p>@quote[0].quote</p>
  }
    }
   

<div  style="display:@display">
 

@if (character != null)
{

    <div >
        <br>
        

       <Character name=@character[0].name/>
        <Character nickname=@character[0].nickname />
             

   

    @for (int i = 0; character[0].occupation.Length > i; i  ){

        string a = character[0].occupation[i];
       <span>@a</span>
       <br/>
    }
        <br />
    @if(character[0].name == "Saul Goodman"){
           
                <img src="https://media.tenor.com/pMhSj9NfCXsAAAAd/saul-goodman-better-call-saul.gif" width="250px" height="250px" />
            
            }else if (character[0].name == "Walter White")
            {
               
            <img src="https://c.tenor.com/0VT7jilszwEAAAAC/mr-white-heisenberg.gif" width="250px" height="250px" />
                

        }
      else{

          
                <img src="@character[0].img" width="250px" height="250px" />
            
        }


    </div>
}else if(character == null){
  
    <div >
        <h3>El personaje introducido no existe, introduce bien el nombre</h3>
    </div>
    
}
  
</div>


</body>


@code {
    string nombre = "";
    Class1[] character;
    Class2[] quote;
    string display = "none";
    bool aratzfag = false;




    async Task GetCharacter(){
        //  var task = await Client.GetFromJsonAsync<Class1>(Endpoints.GetCharacter(nombre));
        // var jsonString = await task.Content.ReadAsStringAsync();
        //  Class1[] result = System.Text.Json.JsonSerializer.Deserialize<Class1[]>(task);

        // Rootobject characterData = await Client.GetFromJsonAsync<Rootobject>(Endpoints.GetCharacter(nombre));
        // characters = System.Text.Json.JsonSerializer.Deserialize<Class1>(Endpoints.GetCharacter(nombre));
        // var a = System.Text.Json.JsonSerializer.Deserialize<List<Class1[]>>(Endpoints.GetCharacter(nombre));

        character = await Client.GetFromJsonAsync<Class1[]>(Endpoints.GetCharacter(nombre));

        if (character.Length == 0){
            character =  null;

        }
        display = "flex";





        //aa = System.Text.Json.JsonSerializer.Deserialize<Class1>(characters);
        // var personaje = Endpoints.GetCharacter(nombre);
        // characters = await Client.GetFromJsonAsync<Rootobject>(Endpoints.GetCharacter(characters1.Property1[0].name));

    }


    
        async Task GetRandomQuote()
        {
        quote = await Client.GetFromJsonAsync<Class2[]>(Endpoints.GetRandomQuote());
        }



}

`


I also tried

`
protected override async Task OnAfterRenderAsync(bool firstRender)
{
        quote = await Client.GetFromJsonAsync<Class2[]>(Endpoints.GetRandomQuote());
 

    }

`

 protected override async Task OnInitializedAsync()

but won't enter in the if statement and show the quote, only when i interact the button. I made sure to debug it and gets the quote from the api but won write it on the page.

Page loaded

After I click the button on the right of the input box

CodePudding user response:

You want the random quote to be shown when opening the page and not change the quote everytime you rerender something, use OnInitializedAsync(). Your first piece of code shows you calling GetRandomQuote (which is async Task) in the UI part without await, this should be called with await in the @code section.

protected override async Task OnInitializedAsync()
{
  await GetRandomQuote();
}
  • Related