Components are great in Blazor, but it is important to understand where and when to use, so that you do not overuse them. In this case you will see how they can be used as list items and we will compare this use case with the one from a previous article.
The example is quite simple, in this case we have Blazor hosted project and we display bank details for the user.
First we have some shared models — one for user details and one for bank details.
In the API project, we have a class called FakeDatabase, which contains two lists of our models. This will be the data retrieved and displayed.
In the controller we have a couple of routes — one for retrieving user data and the other for bank data. Normally, when you retrieve separate pieces of data, you want to use separate routes, actions, procedures for them.
The client part basically contains all the default stuff, except for the new UserComponent.razor file.
The code section for the model contains a parameter for the user and then a variable for bank details to be displayed. The user details a passed through to the component when the list is generated, we will look at that later. But, in the component, we retrieve bank details. This kind of asynchronous process allows you show some data before the other pieces are loaded and if the loading times are slow, perhaps even prevent some frustration.
The html is a piece of a table, in other words — the component is a row of a table.
For the main page, we simply have a list of users and then on initialization we simply retrieve the data and assign it to the list.
Main page also contain the table, in which we have rows being generated as components.
As you can see, there is quite a bit of code in those two files and had it been in one file — it would be a lot more difficult to find what you need. Also, we must not forget that this is just a sample, it is more than likely that a real world project would contain a lot more code than this. Having said all that, the big difference between this example and the one you have seen in the previous article, is the fact that we retrieve two pieces of data here, whilst in the previous it was only one. This makes a huge difference and there is certainly nothing wrong to go with no components implementation. But whenever you have an option two divide the data, you should jump on that opportunity. Another reason, as mentioned previously — is the loading time. If one piece takes longer to retrieve than the other, it is always better to provide users with a bit of a teaser — that being the first piece or pieces of data.