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.