0
votes

I've tried different ways to prevent this from happening.

After changing to render-mode="Server" I was able to prevent rendering twice on the first load.

But now when I refresh the page it still doubles the amount of elements.

Here is what I've got

<div id="component-wrapper" class="row">
    @if (Items != null)
    {
        @foreach (var item in Items )
        {
            <ItemComponent Item="@item" />
        }
    }
</div>

@code {

    [Inject]
    private IItemService ItemService { get; set; }
    List<ItemViewModel> Items { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Items = await ItemService.GetItemsAsync();
        base.OnInitialized();
    }
}

I've read over the Stateful reconnection after prerendering section and it doesn't seem to work for me.

3
"when I refresh the page it still doubles the amount of elements"?? Are you saying that Items contains everything twice and thus foreach doubles up on ItemComponent? Is so check 'GetItemsAsync. ' Also note that when the Blazor Server SPA first loads it calls the page twice - the first time to statically render the page on the server, then a second time when the client side Blazor code calls back to the Blazor Hub to get a fully wired up page. - MrC aka Shaun Curtis

3 Answers

1
votes

For me it was that this script was duplicated on _Hosts.cshtml

<script src="_framework/blazor.server.js"></script>

After deleting one of them problem was solved.

0
votes

Turns out in a further down stream service where I've added to the list, I wasn't creating an empty list to begin with.

Thanks for assisting.

0
votes

Don't override OnInitialized Use OnAfterRender or OnAfterRenderAsync

protected override async Task OnAfterRenderAsync(bool firstRender)

With firstRender you get the info. You can also use our own mecanism to avoid loading your context more than one time.

If needed call StateHasChanged to update the DOM.

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0

EDIT

The easiest way to solve this problem is to use browser localstorage. You can save user id and then get it back in case of a refresh. If a user press F5 to refresh the page, blazor will create a new circuit and there is no easy solution on the server side.