Skip to content
This repository has been archived by the owner on Apr 29, 2021. It is now read-only.

Commit

Permalink
Forbid error with mutated key
Browse files Browse the repository at this point in the history
Because we rewrite the order to have the key before the other
attributes, it’s possible to have the incorrect value for `key` if the
other attribute mutates the key value.  i.e.

```js
var i = 0;
function render() {
return <div attr={i++} key={i++} />;
}
```

Should have `key=1`, but it would actually have `key=0`
  • Loading branch information
jridgewell committed Nov 23, 2016
1 parent f88a84a commit 08c54e5
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/helpers/extract-open-arguments.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ export default function extractOpenArguments(path, plugin) {

// If it's not a literal key, we must assign it in the statics array.
if (!literal) {
if (attrs.length) {
throw attribute.buildCodeFrameError("Key should always be the first computed attribute.");
}

if (!value.isIdentifier()) {
node = value.scope.maybeGenerateMemoised(node);
key = t.assignmentExpression("=", node, key);
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/error/key/other-attr-updates-key/actual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function render() {
return <div attr={i++} key={i++} />;
}
3 changes: 3 additions & 0 deletions test/fixtures/error/key/other-attr-updates-key/options.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"throws": "Key should always be the first computed attribute."
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function render() {
return <div {...props} key={props.key++} />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"throws": "Key should always be the first computed attribute."
}

0 comments on commit 08c54e5

Please sign in to comment.