'How can I update the number of items in the shoppingcart in Blazor Server using LocalStorage?
I have a shopping cart in Blazor Server project and I'm want to update the shoppingcart count everytime a product is added to the cart. I'm using localStorage to store the product. when I try to update the number of items in the cart I get an error:
System.InvalidOperationException: 'IJSInProcessRuntime not available'
Updating shopping cart in the Navigation bar:
<div class="top-row px-4">
<a href="cart" >
<span>
<i class="bi bi-cart"></i> @GetCartItemsCount()
</span>
</a>
</div>
@code {
[Inject] public ISyncLocalStorageService LocalStorage { get; set; }
[Inject] public ICartService CartService { get; set; }
protected override void OnInitialized()
{
CartService.OnChange += StateHasChanged;
}
private int GetCartItemsCount()
{
var cart = LocalStorage.GetItem<List<ShoppingCart>>(SD.ShoppingCart);
return cart == null ? 0 : cart.Count;
}
public void Dispose()
{
CartService.OnChange -= StateHasChanged;
}
}
In CartService I update the localstorage:
public class CartService : ICartService
{
private readonly ILocalStorageService localStorage;
public event Action OnChange;
public CartService(ILocalStorageService localStorage)
{
this.localStorage = localStorage;
}
public async Task DecrementCart(ShoppingCart cartToDecrement)
{
var cart = await localStorage.GetItemAsync<List<ShoppingCart>>(SD.ShoppingCart);
for (int i = 0; i < cart.Count; i++)
{
if (cart[i].ProductId == cartToDecrement.ProductId && cart[i].ProductVariantId == cartToDecrement.ProductVariantId)
{
if (cart[i].Count == 1 || cart[i].Count == 0)
{
cart.Remove(cart[i]);
}
else
{
cart[i].Count -= cartToDecrement.Count;
}
}
}
await localStorage.SetItemAsync(SD.ShoppingCart, cart);
OnChange.Invoke();
}
How can I update the numer of products in the shoppingcart? Thank you in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
