Skip to content

Commit a7d9ea7

Browse files
committed
MudCodeInput: Fix Crash when Initialize with Pre Defined Value
1 parent 533f2ff commit a7d9ea7

1 file changed

Lines changed: 37 additions & 4 deletions

File tree

src/CodeBeam.MudBlazor.Extensions/Components/CodeInput/MudCodeInput.razor.cs

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,20 @@ public MudCodeInput()
3131
private readonly ParameterState<T?> _theValue;
3232
private readonly ParameterState<int> _count;
3333

34+
private bool _pendingSetValue;
35+
private T? _pendingValue;
3436
private async Task OnValueChanged()
3537
{
36-
await SetValueFromOutside(_theValue.Value);
38+
_pendingValue = _theValue.Value;
39+
40+
if (_rendered)
41+
{
42+
await SetValueFromOutside(_pendingValue);
43+
}
44+
else
45+
{
46+
_pendingSetValue = true;
47+
}
3748
}
3849

3950
private async Task OnCountChanged()
@@ -270,15 +281,31 @@ public async Task FocusPrevious()
270281
await _elementReferences[_lastFocusedIndex - 1].FocusAsync();
271282
}
272283

273-
/// <summary>
274-
///
275-
/// </summary>
284+
/// <inheritdoc />
276285
protected override void OnInitialized()
277286
{
278287
base.OnInitialized();
279288
SyncReferences();
280289
}
281290

291+
private bool _rendered = false;
292+
/// <inheritdoc />
293+
protected override async Task OnAfterRenderAsync(bool firstRender)
294+
{
295+
await base.OnAfterRenderAsync(firstRender);
296+
297+
if (firstRender)
298+
{
299+
_rendered = true;
300+
}
301+
302+
if (_pendingSetValue)
303+
{
304+
_pendingSetValue = false;
305+
await SetValueFromOutside(_pendingValue);
306+
}
307+
}
308+
282309
private void SyncReferences()
283310
{
284311
_elementReferences.Clear();
@@ -316,6 +343,9 @@ public async Task SetValue()
316343
/// <returns></returns>
317344
public async Task SetValueFromOutside(T? value)
318345
{
346+
if (!_rendered)
347+
return;
348+
319349
string? val = ConvertSet(value);
320350
if (_count.Value < val?.Length)
321351
{
@@ -324,6 +354,9 @@ public async Task SetValueFromOutside(T? value)
324354
await _theValue.SetValueAsync(base.ConvertGet(val));
325355
for (int i = 0; i < _count.Value; i++)
326356
{
357+
if (_elementReferences[i] == null)
358+
continue;
359+
327360
if (i < val?.Length)
328361
{
329362
await _elementReferences[i].SetText(val[i].ToString());

0 commit comments

Comments
 (0)