Search code examples
c#.net-coreblazorblazor-server-sidesession-storage

How to after refresh page resetting value in blazor?


I want get current use login when sore in ISessionStorageService normal work after user go to Dashboard page, Dashboard have a layout in layout page get SessionStorage value for current user login,

Layout Page

h1>@UserInfo.FullName</h1>

@Body

@code {

    private LoginUser UserInfo = new LoginUser();

    async Task UpdateUserInfo() => UserInfo = await SessionStorage.GetItemAsync<LoginUser>("LoginUser");

    protected override async Task OnInitializedAsync()
    {
        await UpdateUserInfo();
    }
}

Login Page set value

await SessionStorage.SetItemAsync("LoginUser", loginUser);

Note: user login and switch between pages work but when i want refresh page give a error

InvalidOperationException: JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.


Solution

  • As you are using pre-rendering, you cannot call JavaScript methods while this process is being taken place. Instead set the call to the UpdateUserInfo method in the OnAfterRender(Async) pairs, like this:

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
           if( firstRender )
           {
               await UpdateUserInfo();
               InvokeAsync( () => StateHasChanged());
    
            }
    }
    

    Hope this helps...