The Blazor Way to "share" an object among components, routes, pages, etc

Viewed 26

My application will have the user open a file that will be read by the application, and that file will contain database information that will be stored into an object.

The way I see a Blazor app now is that MainLayout.razor is the component that renders my full page: the navbar and the @Body. I would like the file name I grab from the open dialog box to be passed to my project where I then create my object and fill it with the file information.

I got working where I created the object in one of the blazor component modules, only to realize that I would need to do this for all my modules, that is read and parse my database into an object everytime the user clicks a new tab to load a new component. I would like this reading and parsing of the database to be done once, stored in my object and have that object be available to all potential blazor components in my project.

Where should I define the instance of my object and how should I make that object seen and even be updated by all other components? Is this even possible? Am I passing this object as a parameter, is it part of my routing. I'm not sure how to go about this.

1 Answers

Three ways:

  1. State Class

    Create a class with the properties you want to share. Make the class observable. Don't use property setters to change the values, use a method, that not only updates the state it notifies listeners of the change. This class is provided for injection in program.cs

  2. Cascading Value

    Same as the state class but presented as a cascading value instead of injection. This has the added advantage of being able to scope the listeners of the value within the html hierarchy.

  3. Local or Session Storage

    Use JSInteropt to save values to sessions/local storage. The relevant components need to listen for updates and read the storage.

As you have not provided any code or shown any attempt I only listed a broad outline of ways achieve this. In my opinion for your scenario, option 1 is the best choice.

The link you suggested has no way of notifying listeners. The components will not react to changes that occur after initialising.

Related