Skip to content

Instantly share code, notes, and snippets.

@Demuirgos
Created January 8, 2022 11:32
Show Gist options
  • Save Demuirgos/c8d7f86af9b34e85f3a9939ccd2dede0 to your computer and use it in GitHub Desktop.
Save Demuirgos/c8d7f86af9b34e85f3a9939ccd2dede0 to your computer and use it in GitHub Desktop.
Boilerplate to use LocalStorage in BlazorWasm App
using System.Threading.Tasks;
using Microsoft.JSInterop;
using System.Text.Json;
namespace ClientSide.Services
{
public interface ILocalStorage
{
Task SaveAsync<T>(string name, T item) where T : class;
Task DeleteAsync(string name);
Task<T> FetchAsync<T>(string name) where T : class;
}
public class LocalStorage : ILocalStorage
{
private readonly IJSRuntime jsRuntime;
public LocalStorage(IJSRuntime js) => jsRuntime = js;
public async Task SaveAsync<T>(string name, T item) where T : class
{
var data = JsonSerializer.Serialize<T>(item);
await jsRuntime.InvokeVoidAsync("localStorage.setItem", name, data);
}
public async Task DeleteAsync(string name)
{
await jsRuntime.InvokeAsync<string>("localStorage.removeItem", name);
}
public async Task<T> FetchAsync<T>(string name) where T : class
{
var data = await jsRuntime.InvokeAsync<string>("localStorage.getItem", name);
if(data is not null)
return JsonSerializer.Deserialize<T>(data);
else return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment