blazorblazor-server-side

How to send data from one Blazor component to another


I have a very basic component that fetches students lists and displays them, as you can see below:

@if(result == null) {
  <p> No students found </p>
}else{
  @foreach (var person in result){
    <b> @person.name </b>
  }
}


@code {
  [Parameter] public string Token { get; set; } 
  [Parameter] public string StudentsUrl { get; set; } 
  StudentsModel result;     

  protected override async Task OnInitializedAsync()
  {
    using (HttpClient client = new HttpClient())
    {
      client.DefaultRequestHeaders.Accept.Add(
        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
      );

      client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
        "Basic", Convert.ToBase64String(
          System.Text.ASCIIEncoding.ASCII.GetBytes(
            string.Format("{0}:{1}", "", Token)
          )
        )
      );

      HttpResponseMessage response = client.GetAsync(StudentsUrl).Result;
      response.EnsureSuccessStatusCode();
      string responseData = await response.Content.ReadAsStringAsync(); 
      result = JsonConvert.DeserializeObject<StudentsModel>(responseData);
    }
  }
}

The component does it job well, but I need to use the data shown below in another component. The other component has a dropdown (<select> </select> tags) and inside these tags I want to display users list (i.e. @person.name)

So, my question is how do I avoid fetching the same API twice in two different components and simple use the data that is generated in this class, so I can use it in another component.


Solution

  • Expanding upon the comment of @Brian Parker

    You can do it in different ways depends upon you,

    1. Dependency Injection.

    First, Make a Model named Person.cs

    public class Person
        {
            private List<string> name { get; set; } 
        }
    

    Second, Then Goto Program.cs and register it as a service like this, builder.Services.AddScoped<Person>();

    Third, Inject it into your Parent Component, @inject Person _person;

    Last, Do a API call and save that data into this _person.

    Then in your Other Component just inject this service again and it will give you that data since its registered as a scopped service.