0

I have strange situation. I create service which work with local stroge and use js file for this. I want to use getAsync fucntion.

localStorage.js

function get(key) {
    console.log('getItem')
    return localStorage.getItem(key)
}

ILocalStorageService.cs

public async Task<T> GetAsync<T>(string key) where T : class
    {
        var data = await jsRuntime.InvokeAsync<string>("get", key);
        Console.Write("getItem");
        if (string.IsNullOrEmpty(data)) 
        { Console.WriteLine("LocalStorageService: token is null"); return null; }
        return JsonSerializer.Deserialize<T>(data);
    }

I call this function for get autoriaztion token, which I keep in local storage. This token is object, which have 3 fields. And I call this twice:

First, in autorization on loading page

var token = await localStorageService.GetAsync<Token>(nameof(Token));

Second, when I want to get field value

var operatorToken = await localStorageService.GetAsync<Token>(nameof(Token));
Guid operatorID = Guid.Parse(operatorToken.UserID);
Console.WriteLine("Operator is get");

Token.cs

public class Token
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string UserSurname { get; set; }
}

In first I get this token, all work correctly. But in second I just get nothing, no errors, no values. How can you see, I use some logs and in chrome console I see 2 'getItem'. It means I call local storage twice, how I want. But I haven't "Operator is get" in my console. Also I debug this step by step and when I go var data = await jsRuntime.InvokeAsync<string>("get", key); debuging just end. Why I not get value in second situatiob and how to fix this?

  • see - https://stackoverflow.com/questions/75634022/how-to-grab-data-from-protected-local-storage-blazor-server and https://stackoverflow.com/questions/75632049/in-blazor-server-net7-how-do-you-grab-data-from-protectedlocalstorage – MrC aka Shaun Curtis Mar 07 '23 at 14:32
  • @MrCakaShaunCurtis it's not help. I try diffent way to use localStorage. ProtectedLocalStorage from Microsoft, custom localStorage how in question, ```jsRuntime.InvokeAsync("localStorage.getItem)"```. That's all not work. When I want get value from localStorage second time in one page, I can't do this. – Roman Nichi Mar 10 '23 at 07:07
  • It should work. WASM or Server? WASM I suspect. Check that the token exists in the browser using F12 browser tools. Also show your Token class and I'll try to add some demo code as a answer. – MrC aka Shaun Curtis Mar 10 '23 at 08:24
  • @MrCakaShaunCurtis It's Blazor Server. LocalStorage have Token field and keep three value, how I want it. It's work correct. Token is simple class, which contain three public field. I add class to question. – Roman Nichi Mar 10 '23 at 10:27

0 Answers0