Working on my GitHubDashboard Blazor application I soon realized that I need to interact in one way or another with the browser’s local storage. If you missed my previous posts, the main idea of this application is to be “as single page as possible” even if running on the server side hosting model and therefore I chose to go for an Angular inspired architecture. Long story short, I needed a way to persist the token I receive from GitHub so that user’s don’t need to login again if they refresh the page. And, of course I didn’t want to “talk” to the server to achieve this. The natural choice was to use the browser’s local storage.
Using Blazored LocalStorage
It’s very easy to use this library since the only thing you really need to do is install the NuGet package and add the BlazoredLocalStorage service to the DI container. Using this library you can easily add items to the local storage, update them, read them, clear the storage and so on. And all these features are available through both synchronous and asynchronous APIs.
Using Blazored LocalStorage in server-side Blazor apps
Async or not?
During the training courses I deliver for people who want to learn coding every time I get to the point to speak about async and await I tell my students the following: “everytime you do something that is slower than the CPU, you should use async“. That’s why when in the server-side hosting model, I think it’s best to always use async methods where possible (Blazored included).
The same recommendation also applies for the client-side hosting model. Why? Well because local storage items are mostly stored on disk. This means that each time you read or write something from or to the local storage, this information is also written on disk. Sticking to previously described principle, writing or reading to disk is slower then the CPU so there fore async methods are highly recommended.
Working with local storage in Blazor application is made easy by the Blazored library. If you pay attention to the hosting model of your app, working with local storage should be a piece of cake and this opens a lot of opportunities to you Blazor applications. If you experienced other caveats or challenges working with local storage I would be really happy if you could drop a comment. Cheers!
How useful was this post?
Click on a star to rate it!
Average rating / 5. Vote count:
Latest posts by Dan Patrascu-Baba (see all)
- Equality in C#: Part 2 – Value equality - 18/07/2019
- Equality in C#: Part 1- Equality types and reference equality - 16/07/2019
- Integrating chessboards in your Blazor app - 04/07/2019