Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/cloudcrate/BlazorStorage

A library for Blazor local and session storage support.
https://github.com/cloudcrate/BlazorStorage

asp-net-core blazor local localstorage session sessionstorage storage

Last synced: 3 months ago
JSON representation

A library for Blazor local and session storage support.

Lists

README

        

# Blazor Local and Session Storage Support

## Installation

```powershell
PM> Install-Package Cloudcrate.AspNetCore.Blazor.Browser.Storage
```

## See it in Action

Check out [Steve Sanderson's demo at NDC Minnesota, at minute 48](https://youtu.be/JU-6pAxqAa4?t=2875)

## Usage

Add Services to Dependency Injection

```csharp
services.AddStorage();
```

Add Javascript file to your `index.html` or `_Host.cshtml` page in `` after either `` or `` depending on what architecture you are using.

```html

```

## Client-Side

Inject and use Storage

```razor
@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage

Set
Get

@code
{
string value;

void SetValue()
{
Storage.SetItem("storageKey", value);
}

void GetValue()
{
value = Storage.GetItem("storageKey");
}
}
```

## Server-Side

Inject and use Storage

```razor
@using Cloudcrate.AspNetCore.Blazor.Browser.Storage;
@inject LocalStorage Storage

Set
Get

@code
{
string value;

async Task SetValue()
{
await Storage.SetItemAsync("storageKey", value);
}

async Task GetValue()
{
value = await Storage.GetItemAsync("storageKey");
}
}
```

## Events

Using `storage` native event: [StorageEvent](https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent)

```csharp
protected override void OnInit()
{
Storage.StorageChanged += HandleStorageChanged;
}

void HandleStorageChanged(object sender, StorageEventArgs e)
{
Console.WriteLine($"Value for key {e.Key} changed from {e.OldValue} to {e.NewValue}");
}

public void Dispose()
{
Storage.StorageChanged -= HandleStorageChanged;
}
```

## Contributors

* StorageEvent implementation by [@peterblazejewicz](https://github.com/peterblazejewicz)
* Server-side support by [@konradbartecki](https://github.com/konradbartecki/)