Reputation: 351
When using EventCallback in my component, the params for the control are sent again / not updated correctly.
<button @onclick="@(e => ChangePlaceholder())">Change Placeholder</button>
<button @onclick="@(e => ChangePlaceholderEvent())">Change Placeholder Event</button>
<label>@Placeholder</label>
@code {
[Parameter]
public string Placeholder { get; set; }
[Parameter]
public EventCallback<string> OnChanged { get; set; }
private void ChangePlaceholder()
{
Placeholder = "hello";
}
private void ChangePlaceholderEvent()
{
Placeholder = "hello";
OnSelectedChanged.InvokeAsync(Placeholder);
}
}
<Control Placeholder="something" OnChanged=@UpdateSomething />
@code {
static void UpdateSomething(string someString)
{
Console.WriteLine($"Event went kablam: {someString}");
}
}
If you were to run the ChangePlaceholder() function then the UI updates and changes the say 'hello', but if you run the ChangePlaceholderEvent() function, the label goes back to 'something' which is the string that the Placeholder param is sent in the first place.
This leads me to believe that EventCallback being triggered also makes the other params for the control to be sent again.
How can I stop the params being sent again?
Edit: I made a webassemby app and tested the same code and the same bug is occurring.
Upvotes: 0
Views: 663
Reputation: 466
Event callbacks will trigger a re-render of the parent component and you are unconditionally passing down "something" which is what is causing "something" to be re-rendered.
The problem here is that you are using a parameter as state for your component, which you should avoid.
You could get around your problem by using 'Action' instead of 'EventCallback':
[Parameter]
public Action<string> OnChanged { get; set; }
@code {
private void ChangePlaceholderEvent()
{
Placeholder = "hello";
OnChanged(Placeholder);
}
}
Upvotes: 1