1

In Blazor server-side, I have this line of code that retrieves a serialized service from the browser's localstorage (or sessionstorage) using JavaScript interop:

viewData.Cart = await jsInterop.GetJson<Cart>("Cart", BrowserStorageMode.SessionStorage);

I put the deserialized service into a property in a custom scoped service (named ViewData) so that in other places I inject ViewData and use the stored service.

As everyone knows, this line of code, since it uses JavaScript interop can not be in layout's OnInitialized() lifecycle method, because it doesn't work at this stage. so I put it in the OnAfterRender() in an if (firstRender == true) block.

The problem is, If I want to receive the service in a content page, since the lifecycle of the page is executed sooner than the layout page (I checked it using breakpoints), the service in the "content page" is not yet available in both OnInitialized and OnAfterRender(firstRender).

This test that I made is useful when the site first loads or the user refreshes the page, Because I want user's cart is not lost. So how to solve this problem.

Amal K
  • 4,359
  • 2
  • 22
  • 44
mz1378
  • 1,957
  • 4
  • 20
  • 40
  • This comment does not really answer your question. But as I’ve been confronted to the same challenge, I share this information. I don’t use BrowserStorageMode.SessionStorage to store any user data, but static dictionaries at server side. I identify the user by a guid coming from a session cookie. I’ve explained this design on https://stackoverflow.com/questions/67938642/blazor-server-how-to-persist-data-across-multiple-tabs-and-refreshes. The advantage is the guid is directly known by the server side code without waiting for the readiness of jsInterop. –  Jun 23 '21 at 16:07
  • one solution is : in your _Host.cshtml file change render-mode="ServerPrerendered" to render-mode="Static" Solution – Ali Borjian Jun 24 '21 at 10:19

0 Answers0