I have an Ecommerce Blazor Server project and I want to re-render the Cart component after adding a item to the Cart from a Product Component. I tried to inherits the Cart component to Product component and run a public method of Cart component to re-render its component.
The Add to cart method in Product Component.
Product.Razor
public async Task AddToCart()
{
//The adding logic in this area
StateHasChanged();
Reload(); // this method is inherited from the Cart Component trying to re-render the Cart Component
//Does not work
}
Cart.Razor
[Parameter]
public List<Models.Cart> CartItem { get; set; }
protected override void OnInitialized()
{
CartItem = _context.Cart.Where(i => i.CustomUserId == _userManager.GetUserId(_httpContextAccessor.HttpContext.User) && !i.IsSold).ToList();
}
public void Reload()
{
OnInitialized();
StateHasChanged();
}
The method run through successfully but the UI is not re-rendered like the way I want it to be.
I though the UI will re-render when I run the OnInitialized() method and StateHasChanged()?
Thank you.
Edit: I update my Reload() method and call that at the end of AddToCart() method but it doesn't work :(
Cart.Razor
protected override void OnParametersSet()
{
CartItem = _context.Cart.Where(i => i.CustomUserId == _userManager.GetUserId(_httpContextAccessor.HttpContext.User) && !i.IsSold).ToList();
}
public void Reload()
{
OnParametersSet(); //updated but still not working
StateHasChanged();
}
Product.Razor
public async Task AddToCart()
{
//The adding logic in this area
Reload(); // this method is inherited from the Cart Component trying to re-render the Cart Component
//Does not work
StateHasChanged();
}