John
John

Reputation: 301

How do I read and write to the local storage in Blazor server side using Blazored?

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?

Upvotes: 4

Views: 3960

Answers (1)

John
John

Reputation: 301

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

Upvotes: 1

Related Questions