Render when state changes
I have simple component that shows the UserName. Another authentication js library displays an IFrame and in the OnLogin Method I update the UserName. But because no event in the UI triggers this, the component does not Re-Render.
How can I get this to re-render when the state changes?
Just to confirm to myself the UserName was set I added the button which when clicking will trigger a re-render and properly show the UserName.
@inherits AppHeaderModel
<header class="top-row px-4">
<span class="ml-md-auto">@UserName</span>
<button class="btn btn-primary" onclick="@StateHasChanged">Click me</button>
</header>
If you're updating the UserName from JS, you should be able to use the Javascript interop to call back to .NET and have it re-render using StateHasChanged().
If you are updating UserName from C#, can't you just call StateHasChanged() directly after?
If I'm not fully understanding the context, let me know.
It is via Js Interop that I call back to .Net and from there I update the UserName. But the code that updates the UserName doesn't know which components are displaying its value. So you don't know where to call StateHasChanged().
I am not using SignalR but it is a good example. Say SignalR sends a message to change some value and that value is being displayed in a component. How could the SignalR handler know which components to update and even if it did know how could it get an instance of them?
So you have to do some pub sub type option I think. Just wondering how others are solving this.
I use a client service component with events to address this scenario. So in your example the service would have a UsernameChanged event handler which your username module would subscribe to. The service also has a RaiseUsernameChanged() method that you would call after the username is updated. RaiseUsernameChanged() fires (Invokes) the UsernameChanged handler(s) and your username component calls StateHasChanged(). Blazor services are implemented using the built-in DI support. Here's some good docs on Blazor DI and services: https://learn-blazor.com/architecture/dependency-injection/
Thanks for answering, @zbecknell and @JoelW187!
Thanks guys for the input. I will give it a go.
@JoelW187 Would you be kind enough to share an example? I have been trying to figure it out for the past couple of days but no luck.