Reader small image

You're reading from  Mastering Blazor WebAssembly

Product typeBook
Published inAug 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235103
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Mozaffar
Ahmad Mozaffar
author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar

Right arrow

Managing Application State

While a user is using an app, there is a high probability that the user will close the browser by mistake, move to another app, or even expect the app to be in the same flow after refreshing the page or opening the link in another tab.

Managing state is about keeping your app and the user experience consistent, bulletproof, and enjoyable. It’s about keeping track of what the user was doing, even if something unexpected happens.

This chapter teaches you about state management, and the various ways to store and transfer this state, either by using local storage, the URL, or in-memory solutions.

While learning about state management techniques, we will apply them directly to our BooksStore project to preserve the state of the navigated page on the Index page. In addition, we will learn how to keep the state of the new book form, so that if the admin device faced an issue and the app closed suddenly, when the admin navigates to the form again...

Technical requirements

The code used throughout this chapter is available in the book’s GitHub repository:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_07/ChapterContent

The finalized and cleaned version is available at the following URL:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_07/Final

What is state management?

When consumers use your software, they perform certain tasks that the application enables, such as adding items to a shopping cart, filling in forms, dragging events to a calendar, and more. These kinds of tasks produce data, and this data can be stored permanently (in a database on the server via an API; you can learn more about that in detail in Chapter 8, Consuming Web APIs from Blazor WebAssembly) or we can hold this state temporarily in a local source. In this chapter, we are focusing on the second option, which is storing the data temporarily, but before we proceed with doing that, let’s understand the difference between storing on the server or locally, in addition to when to do so and why.

Basically, your software produces data, and this data can be stored in a database on the server. In the case of our bookstore, we need to store books on the server and retrieve them from there.

While developing with Blazor WebAssembly, your app needs...

Persisting the state in the browser’s local storage

Most modern browsers have built-in mechanisms for storing data. This storage is local storage, which is used to store the data for the application across tabs. Even after closing the browser and opening it multiple times, the data stays there.

Another option is session storage, which stores the data for a specific session in a single browser tab. If the user reloads the tab, the data persists, but each tab has its own data for the app and the data is not shared across tabs. Also, browsers have a built-in web API to store a significant number of objects in the JSON format, called IndexedDB. This is an additional option for local and session storage and a very good choice for storing records of data and querying them offline during the app’s lifetime.

Now, let’s go over a practical example of storing the data in local storage.

In the following practice, we are going to implement a great feature in our BooksStore...

Persisting the state in the memory

Using in-memory objects and instances is another option for keeping the state of the app synchronized across the components and instances.

We can achieve this by creating a class that has the property to be stored, a delegate so that the consumer components can subscribe to it to execute some logic when its value changes, and an update method, which sets the value of the property and triggers the delegate.

After creating the class, we register an instance of it in the dependency injection container as a singleton, which will be a single instance created when the app is loaded in the browser, and the same instance is used when any component or service injects the object.

One component can call the Update method and pass the value, and other components can be listeners for the change by subscribing to the delegate and executing some logic in reaction to the value change.

Let’s take a scenario of an app that has certain dashboards...

Persisting the state using the URL

The URL is used mainly for navigation between the app pages, but we have already seen in Chapter 4, Navigation and Routing, how we can send data in the URL to other components and pages.

The same techniques we used, such as the routing parameters or query parameters to transfer data, are also used to keep the flow and the state of the app.

A common example that you may face in every app you build is having a page where there is a list of data to show, just like the Index page of our BooksStore app, which renders a list of books.

The list can be long, so pagination is the solution; each page shows a chunk of the books, and the user can navigate between the pages.

For a good user experience and to make the app easier to use, you need to keep the state of the current page that the user is navigating. When the user refreshes the page, shares the link, or opens it in another tab or browser, the same chunk of data will be listed, and the state...

Summary

In this chapter, we learned how we can keep the user experience as consistent as possible, as well as keeping it safe by persisting the state of the app.

We started by defining what state management is and then we discovered the possible ways to persist the flow of what the user was doing, from browser storage to an in-memory approach, and finally, using the URL.

Alongside the explanation, we explored three practical examples that added powerful features to our app, from storing the data the user is filling in to keep it safe for any surprise event to using the URL to store the current page number that the user has navigated to.

After going through this chapter, you should be able to do the following:

  • Define the importance of state management
  • Know how to use the local storage of the browser
  • Know how to save the state of the app using in-memory objects and dependency injection
  • Use query parameters to store the current state of the page and the flow...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blazor WebAssembly
Published in: Aug 2023Publisher: PacktISBN-13: 9781803235103
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar