Skip to content

Commit 85dd600

Browse files
authored
Add protected browser storage example (#36846)
1 parent a529bd1 commit 85dd600

1 file changed

Lines changed: 46 additions & 1 deletion

File tree

aspnetcore/blazor/state-management/protected-browser-storage.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,52 @@ When prerendering is disabled, [prerendering of `<head>` content](xref:blazor/co
224224

225225
Prerendering might be useful for other pages that don't use `localStorage` or `sessionStorage`. To retain prerendering, defer the loading operation until the browser is connected to the circuit. The following is an example for storing a counter value:
226226

227-
:::moniker range=">= aspnetcore-5.0"
227+
:::moniker range=">= aspnetcore-9.0"
228+
229+
```razor
230+
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
231+
@inject ProtectedLocalStorage ProtectedLocalStore
232+
233+
@if (RendererInfo.IsInteractive)
234+
{
235+
<p>Current count: <strong>@currentCount</strong></p>
236+
<button @onclick="IncrementCount">Increment</button>
237+
}
238+
else
239+
{
240+
<p>Loading...</p>
241+
}
242+
243+
@code {
244+
private int currentCount;
245+
246+
protected override async Task OnInitializedAsync()
247+
{
248+
if (RendererInfo.IsInteractive)
249+
{
250+
await LoadStateAsync();
251+
}
252+
}
253+
254+
private async Task LoadStateAsync()
255+
{
256+
var result = await ProtectedLocalStore.GetAsync<int>("count");
257+
currentCount = result.Success ? result.Value : 0;
258+
}
259+
260+
private async Task IncrementCount()
261+
{
262+
currentCount++;
263+
await ProtectedLocalStore.SetAsync("count", currentCount);
264+
}
265+
}
266+
```
267+
268+
For more information on <xref:Microsoft.AspNetCore.Components.RendererInfo.IsInteractive?displayProperty=nameWithType>, see <xref:blazor/components/render-modes#detect-rendering-location-interactivity-and-assigned-render-mode-at-runtime>.
269+
270+
:::moniker-end
271+
272+
:::moniker range=">= aspnetcore-5.0 < aspnetcore-9.0"
228273

229274
```razor
230275
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage

0 commit comments

Comments
 (0)