Files
ECommerce.RCL/Services/ShopStateService.cs

60 lines
1.5 KiB
C#

using Blazored.LocalStorage;
namespace ECommerceModule.Services;
public class ShopStateService
{
private readonly ILocalStorageService _localStorage;
// keys
private const string FavoritesKey = "shop_favorites";
private const string CategoryIdKey = "shop_category_id";
// events
public event Action? OnChange;
public ShopStateService(ILocalStorageService localStorage)
{
_localStorage = localStorage;
}
public List<string> Favorites { get; private set; } = new();
public Guid? CategoryId { get; private set; }
public async Task InitializeAsync()
{
Favorites = await _localStorage.GetItemAsync<List<string>>(FavoritesKey) ?? new List<string>();
CategoryId = await _localStorage.GetItemAsync<Guid?>(CategoryIdKey);
NotifyStateChanged();
}
public async Task ToggleFavorite(string productId)
{
if (Favorites.Contains(productId))
{
Favorites.Remove(productId);
}
else
{
Favorites.Add(productId);
}
await _localStorage.SetItemAsync(FavoritesKey, Favorites);
NotifyStateChanged();
}
public bool IsFavorite(string productId)
{
return Favorites.Contains(productId);
}
public async Task SetCategoryId(Guid? categoryId)
{
CategoryId = categoryId;
await _localStorage.SetItemAsync(CategoryIdKey, CategoryId);
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}