@page "/MyRecipes"
@using Microsoft.AspNetCore.Authorization;
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
@using MyRecipes2.Shared;
@attribute [Authorize];
@inject HttpClient Http;
@inject AuthenticationStateProvider AuthenticationStateProvider;
@inject NavigationManager NavManager;
<h1>My Recipes</h1>
@if (recipes == null)
{
<p><em>Loading...</em></p>
}
else
{
<p><h3>You have created @recipes.Count() recipe(s)</h3></p>
<div>
<button @onclick="ClickCreateNew" class="btn btn-primary mb-2" type="button" style="float: right">+ Create a new recipe</button>
</div>
<div>
<table class="table">
<thead>
<tr>
<th>Recipe</th>
<th>Created on</th>
<th>Edit/View/Delete</th>
</tr>
</thead>
<tbody>
@foreach (var recipe in recipes)
{
<tr>
<td>@recipe.Name</td>
<td>@recipe.CreatedDateTime</td>
<td>
<button @onclick="() => ClickEdit(recipe)" class="btn btn-primary">Edit</button>
<button @onclick="() => ClickView(recipe)" class="btn btn-primary">View</button>
<button @onclick="() => OpenDeletePrompt(recipe)" class="btn btn-danger">Delete</button>
</td>
</tr>
}
</tbody>
</table>
</div>
@if (DeletePromptOpen)
{
<Modal Title="You are about to permanently delete a recipe" Text="Are you sure you want to delete this recipe?"
OnClose="@OnDeletePromptClose" PromptType="Modal.ModalType.DeleteCancel"></Modal>
}
}
@code{
List<RecipeDto> recipes;
private RecipeDto _recipeToDelete;
public bool DeletePromptOpen { get; set; }
private async Task OnDeletePromptClose(bool accepted)
{
if (accepted)
{
await Http.DeleteAsync($"Recipe/{_recipeToDelete.Id}");
recipes.Remove(_recipeToDelete);
_recipeToDelete = null;
}
DeletePromptOpen = false;
StateHasChanged();
}
private void OpenDeletePrompt(RecipeDto recipe)
{
DeletePromptOpen = true;
_recipeToDelete = recipe;
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
AuthenticationState authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
try
{
string userId = user.FindFirst(c => c.Type == "sub")?.Value;
recipes = await Http.GetFromJsonAsync<List<RecipeDto>>($"Recipe/MyRecipes/{userId}");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
}
}
protected void ClickEdit(RecipeDto recipe)
{
NavManager.NavigateTo($"/EditRecipe/{recipe.Id}");
}
protected void ClickCreateNew()
{
NavManager.NavigateTo("/CreateRecipe");
}
protected void ClickView(RecipeDto recipe)
{
NavManager.NavigateTo($"ViewRecipe/{recipe.Id}");
}
}