Skip to content

Instantly share code, notes, and snippets.

@Calabonga
Created December 1, 2020 05:19
Show Gist options
  • Save Calabonga/6dc91b55cca59ef0ff68730d0d83cd2a to your computer and use it in GitHub Desktop.
Save Calabonga/6dc91b55cca59ef0ff68730d0d83cd2a to your computer and use it in GitHub Desktop.
Blazor LocalStorageService
public interface ILocalStorageService
{
Task SetAsync<T>(string key, T item) where T: class;
Task SetStringAsync(string key, string value);
Task<T> GetAsync<T>(string key) where T: class;
Task<string> GetStringAsync(string key);
Task RemoveAsync(string key);
}
public class LocalStorageService : ILocalStorageService
{
private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task SetAsync<T>(string key, T item) where T: class
{
var data = JsonSerializer.Serialize(item);
await _jsRuntime.InvokeVoidAsync("set", key, data);
}
public Task SetStringAsync(string key, string value)
{
_jsRuntime.InvokeAsync<string>("set", key, value);
return Task.CompletedTask;
}
public async Task<T> GetAsync<T>(string key) where T: class
{
var data = await _jsRuntime.InvokeAsync<string>("get", key);
if (string.IsNullOrEmpty(data))
{
return null!;
}
return JsonSerializer.Deserialize<T>(data)!;
}
public async Task<string> GetStringAsync(string key)
{
return await _jsRuntime.InvokeAsync<string>("get", key);
}
public Task RemoveAsync(string key)
{
_jsRuntime.InvokeAsync<string>("remove", key);
return Task.CompletedTask;
}
}
function message(e) { alert(e); }
function set(key, value) { localStorage.setItem(key, value); }
function get(key) { return localStorage.getItem(key); }
function remove(key) { return localStorage.removeItem(key); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment