2

Working on a Blazor server side project. I am using Blazored Local Storage for this: https://github.com/Blazored/LocalStorage

I have a dropdown, when a value is selected I want to store the value in local storage so that when the user returns to the page later the dropdown will be at the same value.

To accomplish this I bound the dropdown to the value _store and added a getter and setter. This part works:

private int _store {
            get { return GetStoreValue(); } 
            set { SetStoreValue(value); }
        }

Where it falls apart is the two functions for getting and setting:

private int GetStoreValue()
        {
            var returnValue = 0;
            string storedValue = _storage.GetItemAsync<string>("UserListSelectedStore").ToString();
            if (!string.IsNullOrEmpty(storedValue))
            {
                int storedValueInt = Int32.Parse(storedValue);
                if (storedValueInt > 0)
                {
                    returnValue = storedValueInt;
                }
                else
                {
                    returnValue = _storeValue;
                }
            }
            else
            {
                returnValue = _storeValue;
            }
            return returnValue;
        }

private void SetStoreValue(int value)
        {
            _storage.SetItemAsStringAsync("UserListSelectedStore", value.ToString());
            _storeValue = value;
        }

Essentially, if there is a stored store value, use that. Otherwise return whatever was set when the component was initialized.

The problem - The value of storedValue is always an empty string "". It appears to write the value to storage correctly, but has problems reading it. Since this is a server side project, I have to use async for reading, I am not sure if that is the issue but I tried blindly changing it a few times and couldn't get it to work.

How do I get Blazor to read the stored value and return it if it exists?

Joe
  • 212
  • 2
  • 11
  • 2
    If you look at local storage in your browser do you see it there? If so the problem is with getting it. – Crowcoder Jul 19 '22 at 17:15
  • Don't know why I didn't think of that lol. Looks like it is writing the value, the issue is in reading it. – Joe Jul 19 '22 at 17:33
  • 1
    Do you want to preserve the value for this "SPA Session" or if the user returns to the site say tomorrow? Local Storage fulfils the second option, but is overkill for the first. If it's the first then take a look at this question - https://stackoverflow.com/questions/72952693/my-static-variables-in-my-blazor-server-app-are-keeping-their-values-even-if-i/72955992#72955992 and my answer. – MrC aka Shaun Curtis Jul 19 '22 at 19:05

1 Answers1

1

Figured it out. I needed to add it to the OnInitializedAsync() method so everything gets set before the DOM loads.

Joe
  • 212
  • 2
  • 11