tracked-tools / tracked-built-ins

Tracked versions of JavaScript's built-in classes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`{{#each}}` rerenders on every array `set`

boris-petrov opened this issue · comments

Here is a reproduction.

Every keystroke in the text field causes the loop to rerender and the focus from the textfield to be lost. Check the log - it logs on every keystroke (meaning that the loop redraws).

Adding a key="@index" to the each fixes the problem but that's a "hack" I guess.

The problem is this line. However, removing it will probably cause other issues. So a clever solution should be thought of.

The same behavior occurs if you use standard EmberArray tracking/reactivity:

import { action } from '@ember/object';
import Controller from '@ember/controller';

export default class ApplicationController extends Controller {
  array = ['asd'];

  @action
  setValue(index, event) {
    this.array.replace(0, 1, [event.target.value]);
  }
}

This behavior makes sense, because the value to the each has changed. It needs to rerender each item, and the items are keyed off their identity, which in this case is the string itself. The string has changed, so the item has changed, and it is fully replaced.

You could either pass key="@index" to the each to have it key off the index instead, or you could wrap the string in an object whose identity is stable as you mutate the value.