enet
enet

Reputation: 45596

EditForm seems not to be updated after adding a record, why

Note: This is a question I've migrated from Github issues (See issue)

Here is a project showing the issue in it's simplest form: Code download

  1. Run project.
  2. Note names on index page.
  3. Add a new person with the form.
  4. Notice message proving the newly created person exists in the list in index, but isn't actually rendered in the component.
  5. Navigate to counter and then back to index.
  6. Notice the added person is now in the list.

I have tried both with/without StateHasChanged() calls in both the page and component.

Page:

public void OnCreated(Person person)
{
    _person = person;
    _created = true;
    Fake.People.Add(person);
    StateHasChanged();
}

Component:

private async Task CreateItem()
{
    _item = CreateFormItem<TItem>(_formProperties);
    await OnCreated.InvokeAsync(_item);
    StateHasChanged();
}

Upvotes: 0

Views: 563

Answers (1)

enet
enet

Reputation: 45596

private async Task CreateItem()
{
    _item = CreateFormItem<TItem>(_formProperties);
    await OnCreated.InvokeAsync(_item);
    StateHasChanged();
}

The call to StateHasChanged(); is meaningless here.

public void OnCreated(Person person)
{
    _person = person;
    _created = true;
    Fake.People.Add(person);
    StateHasChanged();
}

I'd do something like this:

public async Task OnCreated(Person person)
   {
       Console.WriteLine(person.FirstName);
       _person = person;
       _created = true;
       Fake.People.Add(person);

       await InvokeAsync( () => StateHasChanged());
       
   }

But the culprit is not the StateHasChanged method

Solution:

Remove this code snippet from the OnInitializedAsync method:

_items = new List<Dictionary<string, object>>();
  foreach (var item in Items) _items.Add(GetItemProperties(item)); 

And place it in the OnParametersSetAsync method:

protected override async Task OnParametersSetAsync()
  {
      await base.OnParametersSetAsync();
     
      _items = new List<Dictionary<string, object>>();
      foreach (var item in Items) _items.Add(GetItemProperties(item));
     
  }

Upvotes: 1

Related Questions