glimmerjs / glimmer-component

[MOVED] This package is now part of the Glimmer.js monorepo
https://github.com/glimmerjs/glimmer.js
51 stars 16 forks source link

`each` helper throwing "Must specify a key" error #4

Closed asakusuma closed 7 years ago

asakusuma commented 7 years ago

A simple each loop doesn't seem to work.

{{#each list}}
  <li>{{this}}</li>
{{/each}}

Repro commit to hello-glimmer

Uncaught Error: Must specify a key for #each
    at Environment$$1.iterableFor (environment.js:175)
    at lists.js:23
    at AppendOpcodes.evaluate (opcodes.js:270)
    at VM.execute (append.js:288)
    at Object.render (template.js:116)
    at App.render (application.js:87)
    at App.boot (application.js:79)
    at index.js:4
rwjblue commented 7 years ago

The default iteratorFor implementation that glimmer-application uses, requires a key to be specified (see here). Ember's version of {{each does this for you automatically by utilizing Ember.guidFor, but in a standalone glimmer environment you must manually specify the key to be used.

{{#each list key="id" as |item|}}
  <li>{{item}}</li>
{{/each}}
asakusuma commented 7 years ago

Is id a reserved word for the index of an array? I'm confused as to what a key is in the context of an array. Array items might have a key, but the entire array? I also don't see this key concept in the handlebars docs.

pittst3r commented 7 years ago

For an array you would use {{#each list key="@index" as |item|}}.

rwjblue commented 7 years ago

They key generally is a property on each item in the array, or as @robbiepitts mentioned you can use the special value "@index".

A similar concept exists in react land, and Ember just makes it slightly easier since it can use guidFor.

pittst3r commented 7 years ago

Yes, sorry, meant to say, "array of non-objects (like strings)".

asakusuma commented 7 years ago

Thanks for the responses. This feels clunky to me, as it seems like we are allowing the complexity of specific scenario (array of objects) to complicate the API for a simple scenario (array of primitives). Is this key property documented anywhere? I don't see it on the handlebars built-in helpers page.

tomdale commented 7 years ago

@asakusuma It's not documented anywhere because documentation for Glimmer doesn't exist yet. :) It is not surprising that it's not on the Handlebars page since this is a concern that only applies to diffing re-renders.

asakusuma commented 7 years ago

To close the loop here, the suggested syntax works. I'm fine closing this, but we may want to leave open as a reminder for something to highlight in the eventual glimmer docs.

acorncom commented 7 years ago

@asakusuma Did I hit this well enough in https://www.glimmerjs.com/guides/templates-and-helpers ? See the bottom of the page ...

locks commented 7 years ago

Closing for now, open an issue in the website repo for further discussion. Gracias :)

asakusuma commented 7 years ago

@acorncom yes, thanks!