-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPersistentProductView.razor
More file actions
75 lines (58 loc) · 2.64 KB
/
PersistentProductView.razor
File metadata and controls
75 lines (58 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@inject GalacticRelicsService GalacticRelicsService
@* to manually persist state from pre-rendering, this must be injected
and the callback to persist state must be disposed using IDisposable *@
@inject PersistentComponentState PersistentState
@implements IDisposable
<div class="p-3">
<h3 class="display-5">@(CategoryName ?? "All Products")</h3>
<CategoryPicker @bind-CategoryId="selectedCategoryId" Categories="categories" />
<ProductGrid Products="products" CategoryId="selectedCategoryId" />
</div>
@code {
List<Product>? products;
List<Category>? categories;
int? selectedCategoryId = null;
string? CategoryName => categories?.FirstOrDefault(c => c.Id == selectedCategoryId)?.Name;
#region Persistent State Management
// Persistent state requires creating a unique key for storing this component's state
string productsKey = $"{nameof(PersistentProductView)}-{nameof(products)}";
string categoriesKey = $"{nameof(PersistentProductView)}-{nameof(categories)}";
PersistingComponentStateSubscription persistentStateSubscription;
private Task PersistComponentState()
{
PersistentState.PersistAsJson(productsKey, products);
PersistentState.PersistAsJson(categoriesKey, categories);
return Task.CompletedTask;
}
private void RestoreComponentState()
{
// check if the state has been persisted
if (PersistentState.TryTakeFromJson(productsKey, out List<Product>? persistedProducts))
{
products = persistedProducts;
}
if (PersistentState.TryTakeFromJson(categoriesKey, out List<Category>? persistedCategories))
{
categories = persistedCategories;
}
}
// the subscription must be disposed to avoid memory leaks
public void Dispose()
{
persistentStateSubscription.Dispose();
}
#endregion Persistent State Management
protected override async Task OnInitializedAsync()
{
// attempt to restore persisted state
RestoreComponentState();
// ??= allows us to only call the API if these are null, e.g. if
// there was no persisted data
products ??= await GalacticRelicsService.GetProductsAsync();
categories ??= await GalacticRelicsService.GetCategoriesAsync();
// manually define what should be persisted with a callback method.
// this subscription must also be disposed, so this component must implement IDisposable.
// according to documentation, this must be called last to avoid a race condition.
persistentStateSubscription = PersistentState.RegisterOnPersisting(PersistComponentState);
}
}