Home > Mobile >  StateHasChanged not updating component
StateHasChanged not updating component

Time:07-09

I have two components, one is used to list all students and the other shows details of a selected student.

Here are the parent components for both:

<p> Id of student @id </p>

<Students onStudentSelected="@getStudentId"> </Students>

<Student StudentId="@id"> </Student>


@code {
    private int id; 

    private void getStudentId (int e) {
        id = e;
        stateHasChanged();
    }
}

Now here is the thing,the <Students> </Students> component works without issue, i.e. I can see list of students and when clicked on one, the id of the student is assigned to id and this is displayed inside the <p></p> tags.

But the <Student> </Student> component is not refreshing. If I manually give the Student component an id then I can see the Student details.

So, for some reason stateHasChanged(); has no effect here.


If you want to see what these two components look like, it is as simple as:

Students

@foreach(var std in StudentsJSON) {
  <p @onclick="() => selectStudent(std.id)"> @std.name </p>
}

@code {
    [Parameter]
    public EventCallback<int> onStudentSelected { get; set; }

    async Task selectStudent(int e){
        await onStudentSelected.InvokeAsync(e)
        // StateHasChanged(); tried here doesn't work
    }
}

Student

@using Newtonsoft.Json 
@using System.Net.Http.Headers

@if(JsonResponseContent == null) {
    <p> No student found </p>
}else{
    
    @foreach(var st in JsonResponseContent) {
      <p> @st.age / @st.name / @st.subject </p>
    }
}


@code {
    [Parameter] public int id { get; set; }

    Student JsonResponseContent; 

    protected override async Task OnInitializedAsync(){
   using (HttpClient client = new HttpClient())
    {
        ...
        JsonResponseContent = JsonConvert.DeserializeObject<Student>(ResponseContent);
    }    
    }
}

I don't know why the refresh is not working.

CodePudding user response:

In Student component call api in OnParametersSetAsync() method

protected override async Task OnParametersSetAsync(){
   using (HttpClient client = new HttpClient())
   {
        ...
        JsonResponseContent = JsonConvert.DeserializeObject<Student(ResponseContent);
    }    
    }
}

OnInitializedAsync gets call only once in component lifecycle while OnParametersSetAsync every time parameter value changes (in your example id). More info.

  • Related