Created
January 8, 2022 11:32
-
-
Save Demuirgos/c8d7f86af9b34e85f3a9939ccd2dede0 to your computer and use it in GitHub Desktop.
Boilerplate to use LocalStorage in BlazorWasm App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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