| | | 1 | | using Microsoft.JSInterop; |
| | | 2 | | |
| | | 3 | | namespace UIBlazor.Services.Settings; |
| | | 4 | | |
| | 0 | 5 | | public class LocalStorageService(IJSRuntime js, ILogger<LocalStorageService> logger) : ILocalStorageService |
| | | 6 | | { |
| | | 7 | | public async Task SetItemAsync<T>(string key, T value) |
| | | 8 | | { |
| | 0 | 9 | | var json = JsonSerializer.Serialize(value); |
| | 0 | 10 | | await js.InvokeVoidAsync("localStorage.setItem", key, json); |
| | 0 | 11 | | } |
| | | 12 | | |
| | | 13 | | public async Task<T?> TryGetItemAsync<T>(string key) |
| | | 14 | | { |
| | | 15 | | try |
| | | 16 | | { |
| | 0 | 17 | | var json = await js.InvokeAsync<string?>("localStorage.getItem", key); |
| | 0 | 18 | | return json == null ? default : JsonSerializer.Deserialize<T>(json); |
| | | 19 | | } |
| | 0 | 20 | | catch (Exception ex) |
| | | 21 | | { |
| | 0 | 22 | | logger.LogError("Error getting item '{key}': {message}", key, ex.Message); |
| | 0 | 23 | | return default; |
| | | 24 | | } |
| | 0 | 25 | | } |
| | | 26 | | |
| | | 27 | | public async Task RemoveItemAsync(string key) |
| | 0 | 28 | | => await js.InvokeAsync<string?>("localStorage.removeItem", key); |
| | | 29 | | |
| | | 30 | | public async Task<List<string>> GetAllKeysAsync() |
| | | 31 | | { |
| | 0 | 32 | | return await js.InvokeAsync<List<string>>("eval", "Object.keys(localStorage)"); |
| | 0 | 33 | | } |
| | | 34 | | } |