I have three components. Component one contains component two and three. Component two is a list. Component three is for adding items to the database.
When I have saved an item to the database I want to update the list in component two. How do I do that?
Let's suppose:
<CRUD>
<GRID/>
<FORM/>
</CRUD>
Using a delegate, you can capture the reference for GRID
component and call a GRID
method from FORM
through a delegate. Try delegate sample at blazorfiddle.
Simplifying:
On CRUD
:
<GRID @ref="mygrid" />
<FORM mydelegate="@( (s) => mygrid.setData(s) )" />
@code
{
protected GRID mygrid;
}
On GRID
:
<h1>@data</h1>
@code
{
string data;
public void setData(string value)
{
data = value;
StateHasChanged();
}
}
On FORM
:
<input @bind-value=@somedata />
<button @onclick="@( () => mydelegate(somedata ?? "hi") )">press</button>
@code
{
[Parameter] public Action<string> mydelegate {set; get;}
string somedata;
}
Just share your list between components. You cal also subscribe GRID
to add
event list. More info at How to handle add to list event?. Of course, you can use also an ObservableCollection. Maybe you can avoid event, just adding to list and call StateHasChanged
may be enough.
Remember you can share the list via parameters or cascade parameter.
<CRUD>
<GRID data=@mylist />
<FORM data=@mylist />
</CRUD>
Do you have several more options like using a singleton via Dependency Injection, eventcallback, ... . I suggest to you to read 3 Ways to Communicate Between Components in Blazor by @Chris Sainty
You should have posted a minimal repo with your question so that we can clearly see the issue you're facing.
However, generally speaking, there are a couple of ways to do this. In one of my answers in the Blazor section I have described three ways how to enable such scenario.
In this answer I'll suggest you to employ the App State Pattern, from which you can manage the state of your components, perform CRUD Actions related to the data in your components, refresh the components, etc.
An excellent sample created by Steve Anderson, which employ the App State Pattern is FlightFinder. This sample (Client project) defines a service named AppState which is injected to a number of components, and provide them with various functionalities. Please, inspect this class, and the components involved, and how they communicate with each other, and apply what you'll learn in your app. Don't hesitate to ask any question.
Note: If you are not acquainted with this sample, learn it thoroughly as this is an excellent way to learn Blazor.
See my answers here and here.
Hope this helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With