Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Passing List<T> between components

I am having issue with the code, I have my page layout as below. I am communicating to database to get data for Main Content. It is List<SomeClass> that I am getting from database. Now I want same List<SomeClass> to be available for RightContent. Both components are custom and have different layout but can share same List rather than making same call twice. (Sequence is MainContent Initialized() method gets called first)

I created a service class AppDataService with below property. Also added to IServiceCollection services in startup.

public List<SomeClass> sharedListOfSomeClass = new List<SomeClass>();

In MainContent I am injecting AppDataService and assigning sharedListOfSomeClass with database values. Now if I am injecting AppDataService in Right Content and and trying to access sharedListOfSomeClass I am getting it as null.

I know I am missing binding here because both the components are different in terms of html and can't bind it to any html tags.

Could any one please help me out to achieve this. I want to make single call to database for both the components.

enter image description here

like image 873
ZKS Avatar asked Apr 11 '20 07:04

ZKS


2 Answers

If you want to have some global state of the app and share it between different components, the most reasonable way to do it is to create a State class that will contain the global state data

public class State
{
    public List<SomeClass> SomeClassObjectsCollection { get; set; } = new List<SomeClass>();
}

In your Startup (or Program if you use Blazor wasm) you should add a State object as a singleton

services.AddSingleton<State>()

and on every page, where you need an access to state (or even in _Imports if you want to access it often) add

@inject State State

After that on any page you can refer to State.SomeClassObjectsCollection and get the same data.

The key point is adding a state as a singleton. If you will add is as transient or even scoped, the dependency container will create new instances of State.

like image 157
Дмитро Іванов Avatar answered Sep 29 '22 08:09

Дмитро Іванов


One option is to pass the list to the components as parameter. Define a parameter in the component's code.

[Parameter] public List<SomeClass> sharedListOfSomeClass { get; set; }

In the parent pass the set the parameter:

<MyCustomComponent sharedListOfSomeClass="@MyVariableHoldingTheListValues" />

Other way I can think of is to make a static list and reference the static list in the components.

The scenario of the injection gives you null because the service could be registered as transient or scoped servervice. Not as singleton.

like image 40
Zsolt Bendes Avatar answered Sep 29 '22 06:09

Zsolt Bendes