Roy Berris
Roy Berris

Reputation: 1572

Blazor make element disappear after x seconds

I build a notification system which shows a bootstrap alert div in a NotificationHandler blazor component. This works fine but the notifications stay there. I'd like to make these notifications disappear after x seconds. How can I do this while not blocking UI and making sure it is executed on the blazor render thread.

See example code below:

@inject INotificationHandler Handler;

@foreach (var notification in _notifications)
{
<div class="alert alert-success">
  <p>@notification</p>
</div>
}

@code
{
  private List<string> _notifications = new ();

  protected override void OnInitialized()
  {
     Handler.OnReceived += OnReceived;
  }

  private async Task OnReceived(string notification)
  {
     await InvokeAsync(() => {
        _notifications.Add(notification);
        StateHasChanged();
        
        // TODO: remove notification the _notifications after x seconds
     });
  }
}
public interface INotificationHandler
{
  public event Func<string Task> OnReceived;
}

Upvotes: 2

Views: 1971

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

await InvokeAsync(async () =>    // note the 'async'
  {  
    _notifications.Add(notification);
    StateHasChanged();
    
    // TODO: remove notification the _notifications after x seconds
    await Task.Delay(2_000);  // x = 2
    _notifications.Remove(notification);
    StateHasChanged();
  });

The calls to StatehasChanged() are needed because OnReceived() is an event that does not belong to the normal Blazor LifeCycle.

The Task.Delay() creates the pause but also allows the new state to be rendered.

Upvotes: 4

Related Questions