.NET 8 Blazor – Page layout OnAfterRenderAsync life-cycle not triggered

Need some advice or guidance. I’m new at using .NET Blazor. I’m trying to configure a sort of auto logout function for my web app. The idea is to have it spin up as a timer when the web page loads and reset the timer each time a client interaction is detected.

The idea was to embed it into the main layout (I think it’s statically rendered), but doing that does not allow me to use the OnAfterRenderAsync(bool firstRender). The life-cycle event never fires. From what I understand, it’s because that life-cycle event only fires for interactive components. So I cant really use that life-cycle event.

Problem I’m having, is that the JSRuntime can’t be accessed if the page has not been completely rendered. I thought I could do a Task.Wait(), but that just seems like bad practice. Other life-cycle events throw a error due to the render state.

CODE

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> public partial class MainLayout : IDisposable
{
private System.Timers.Timer? _timeoutTimer;
[Inject]
private IIdentityService? IdentityService { get; set; }
[Inject]
private IJSRuntime? JSRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// set the timer to 5 minutes
_timeoutTimer = new System.Timers.Timer((int)(1 * 60 * 1000));
_timeoutTimer.Elapsed += TimeoutTimerElapsed;
_timeoutTimer.AutoReset = false;
await JSRuntime!.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this));
}
}
[JSInvokable]
public void TimerInterval()
{
if (_timeoutTimer is null)
ArgumentNullException.ThrowIfNull(_timeoutTimer, nameof(_timeoutTimer));
// resetting the timer if the user is in an active state & restart the timer.
_timeoutTimer.Stop();
_timeoutTimer.Start();
}
private void TimeoutTimerElapsed(object? sender, ElapsedEventArgs e)
{
InvokeAsync(async () => await IdentityService!.LogoutAsync());
}
public void Dispose()
{
if (_timeoutTimer is not null)
_timeoutTimer.Dispose();
}
}
</code>
<code> public partial class MainLayout : IDisposable { private System.Timers.Timer? _timeoutTimer; [Inject] private IIdentityService? IdentityService { get; set; } [Inject] private IJSRuntime? JSRuntime { get; set; } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { // set the timer to 5 minutes _timeoutTimer = new System.Timers.Timer((int)(1 * 60 * 1000)); _timeoutTimer.Elapsed += TimeoutTimerElapsed; _timeoutTimer.AutoReset = false; await JSRuntime!.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this)); } } [JSInvokable] public void TimerInterval() { if (_timeoutTimer is null) ArgumentNullException.ThrowIfNull(_timeoutTimer, nameof(_timeoutTimer)); // resetting the timer if the user is in an active state & restart the timer. _timeoutTimer.Stop(); _timeoutTimer.Start(); } private void TimeoutTimerElapsed(object? sender, ElapsedEventArgs e) { InvokeAsync(async () => await IdentityService!.LogoutAsync()); } public void Dispose() { if (_timeoutTimer is not null) _timeoutTimer.Dispose(); } } </code>
 public partial class MainLayout : IDisposable
 {
     private System.Timers.Timer? _timeoutTimer;

     [Inject]
     private IIdentityService? IdentityService { get; set; }

     [Inject]
     private IJSRuntime? JSRuntime { get; set; }


     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
         if (firstRender)
         {
             // set the timer to 5 minutes
             _timeoutTimer = new System.Timers.Timer((int)(1 * 60 * 1000));
             _timeoutTimer.Elapsed += TimeoutTimerElapsed;
             _timeoutTimer.AutoReset = false;

             await JSRuntime!.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this));
         }
     }

     [JSInvokable]
     public void TimerInterval()
     {
         if (_timeoutTimer is null)
             ArgumentNullException.ThrowIfNull(_timeoutTimer, nameof(_timeoutTimer));

         // resetting the timer if the user is in an active state & restart the timer.
         _timeoutTimer.Stop();
         _timeoutTimer.Start();
     }

     private void TimeoutTimerElapsed(object? sender, ElapsedEventArgs e)
     {
         InvokeAsync(async () => await IdentityService!.LogoutAsync());
     }

     public void Dispose()
     {
         if (_timeoutTimer is not null)
             _timeoutTimer.Dispose();
     }
 }

Javascript

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>function timeOutCall(dotnethelper) {
var eventTypes = ['click', 'mousemove', 'keypress', 'scroll', 'touchstart', 'touchmove'];
var timer;
function resetTimeDelay() {
clearTimeout(timer);
timer = setTimeout(function () { dotnethelper.invokeMethodAsync("TimerInterval"); }, 1000); // Reset the timer after 1 second of inactivity
}
eventTypes.forEach(function (eventType) {
document.addEventListener(eventType, resetTimeDelay);
});
// Remove event listeners when the component is unloaded or the timer is reset
function removeListeners() {
eventTypes.forEach(function (eventType) {
document.removeEventListener(eventType, resetTimeDelay);
});
}
// Return a function to remove event listeners
return removeListeners;
}
</code>
<code>function timeOutCall(dotnethelper) { var eventTypes = ['click', 'mousemove', 'keypress', 'scroll', 'touchstart', 'touchmove']; var timer; function resetTimeDelay() { clearTimeout(timer); timer = setTimeout(function () { dotnethelper.invokeMethodAsync("TimerInterval"); }, 1000); // Reset the timer after 1 second of inactivity } eventTypes.forEach(function (eventType) { document.addEventListener(eventType, resetTimeDelay); }); // Remove event listeners when the component is unloaded or the timer is reset function removeListeners() { eventTypes.forEach(function (eventType) { document.removeEventListener(eventType, resetTimeDelay); }); } // Return a function to remove event listeners return removeListeners; } </code>
function timeOutCall(dotnethelper) {
    var eventTypes = ['click', 'mousemove', 'keypress', 'scroll', 'touchstart', 'touchmove'];
    var timer;

    function resetTimeDelay() {
        clearTimeout(timer);
        timer = setTimeout(function () { dotnethelper.invokeMethodAsync("TimerInterval"); }, 1000); // Reset the timer after 1 second of inactivity
    }

    eventTypes.forEach(function (eventType) {
        document.addEventListener(eventType, resetTimeDelay);
    });

    // Remove event listeners when the component is unloaded or the timer is reset
    function removeListeners() {
        eventTypes.forEach(function (eventType) {
            document.removeEventListener(eventType, resetTimeDelay);
        });
    }

    // Return a function to remove event listeners
    return removeListeners;
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật