aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Render when state changes

Open StevenTCramer opened this issue 8 years ago • 6 comments

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>

StevenTCramer avatar Jul 04 '18 05:07 StevenTCramer

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.

zbecknell avatar Jul 04 '18 13:07 zbecknell

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.

StevenTCramer avatar Jul 04 '18 17:07 StevenTCramer

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/

JoelW187 avatar Jul 05 '18 10:07 JoelW187

Thanks for answering, @zbecknell and @JoelW187!

SteveSandersonMS avatar Jul 05 '18 15:07 SteveSandersonMS

Thanks guys for the input. I will give it a go.

StevenTCramer avatar Jul 06 '18 02:07 StevenTCramer

@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.

PeymanDinani avatar Aug 27 '18 17:08 PeymanDinani