DavidAJohn / BookwormsLendingLibrary

Blazor Server client UI with a .NET Web API backend for an imaginary online library.
https://bookwormslibrary.azurewebsites.net
7 stars 4 forks source link

[Bug] JS Interop error when admin and account pages are refreshed #7

Closed DavidAJohn closed 3 years ago

DavidAJohn commented 3 years ago

The Account/Index page and the Admin/Index page both display JS Interop errors if the user hits refresh in their browser, although the data is displayed correctly on page load.

It seems to be an issue with pre-rendering.

I'm tempted to just say "don't hit refresh on a single page app", but let's see if something can be done, because it looks pretty ugly.

DavidAJohn commented 3 years ago

The error message returned here is really quite useful.

It tells you that because the page is being pre-rendered, the earliest JS Interop can be used is in the OnAfterRenderAsync method. This is a Blazor Server app, don't forget. In a Blazor WASM app, this wouldn't apply.

Both of these pages check for Administrator authorisation at a page level in the UI (and on the API controller method). This is done using local storage to get a JWT auth token via JS Interop.

It has to be done, but can't be used in the OnInitializedAsync method each time the page is reloaded without provoking the error.

DavidAJohn commented 3 years ago

As the error message suggested, I had to move the population of the 'requests' List<> back in the page lifecycle.

So instead of doing this in the OnInitializedAsync method, I moved it to OnAfterRenderAsync.

However, this requires you to put the service call to the API in a separate method, which is then awaited from the OnAfterRenderAsync method.

Crucially, you also need to then call StateHasChanged() to make the page re-render, otherwise it appears that nothing has happened, despite a successful API response and the requests List<>being populated.

It's just a remaining quirk of Blazor that you either know or have to discover.