Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Why isn't sibling component updating its content?

$
0
0

I am developing a Blazor server app. One of the classes is Employee.cs which is injected at Startup.cs

Employee.cs

public class Employee{    public string Name { get; set; } = "James";}

Startup.cs

  ...  ...  services.AddSingleton<Employee>();

To use this injected instance, I wrote a simple component Welcome.razor

Welcome.razor

@inject Employee Emp<h1>Welcome Mr.@Emp.Name</h1>

The Welcome component is a permanent part of the UI, and is displayed at the top of the page.

I created a razor page ChangeName.razor that also displays the Name from the injected instance, and a button to alter the value. When the button is clicked, the name is changed within the page containing the button, but has no effect on the Welcome.razor even after calling StateHasChanged()

ChangeName.razor

@page "/"@inject Employee Emp<button @onclick="@ChangeName">Change Name</button><div>Employee name in page is: @Emp.Name</div>@code {    void ChangeName() {        Emp.Name = "Mike";        StateHasChanged();    // has no effect on the Welcome.razor content    }}

Once the button is clicked, the name in Welcome.razor stays as James but the name in ChangeName.razor page is changed to Mike. Why aren't they synced?

Here is what I did as a work-around:

Welcome.razor

@code {    static Welcome _welcome;    protected override void OnInitialized()    {        base.OnInitialized();        _welcome = this;        // grab a reference to the current instance                                 // and assign it to the static instance    }    public Refresh() {       _welcome.StateHasChanged();    // this can be called from any other component now    }}

Now I can just call Welcome.Refresh() from anywhere and the name will change. But this solution is ugly and there must be something wrong that I am doing..

What can I do to automatically trigger StateHasChanged() for any component that is displaying a shared object?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>