Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Server How to persist data across multiple tabs and refreshes

I am writing a Blazor Server application that needs to persist data for the user.

I have tried the following / the following does not meet the requirements:

  • Session storage - Because it is scoped to the browser tab the data is gone on refresh / not on a new tab.
  • Local storage - Works across multiple tabs and refreshes but stays for future visits to the site (I do not want the data to persist through multiple visits)
  • An AppState approach that is scoped - is once again based on per circuit which is per tab.

Some ideas I had but are unsure how to implement / if they are good ideas:

  • Use local storage but either clear it somehow when the client disconnects or add a time tag in local storage and only allow a persistence of x time.
  • Use cookies somehow maybe via: Creating and Reading Cookies on Blazor Server Side

Other than that I don't have any other good ideas on how to implement this so any ideas / suggestions are welcomed.

like image 544
Kyle Cintron Avatar asked Oct 20 '25 10:10

Kyle Cintron


1 Answers

Well, this is not original to me, but here's how I persist Tenant for the logged in user for as long as they are connected.

public class GlobalService
{
    public event Action<PropertyChangedEventArgs> PropertyChanged;

    Subscriber _Tenant;
    public Subscriber Tenant
    {
        get
        {
            return _Tenant;
        }
        set
        {
            if (!object.Equals(_Tenant, value))
            {
                var args = new PropertyChangedEventArgs() { Name = "Tenant", NewValue = value, OldValue = _Tenant, IsGlobal = true };
                _Tenant = value;
                PropertyChanged?.Invoke(args);
            }
        }
    }
}

public class PropertyChangedEventArgs
{
    public string Name { get; set; }
    public object NewValue { get; set; }
    public object OldValue { get; set; }
    public bool IsGlobal { get; set; }
}

And I register it in ConfigureServices like so

services.TryAddScoped<GlobalService>();
like image 174
John White Avatar answered Oct 21 '25 22:10

John White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!