Explorar o código

Allow undefined inside x-for

Caleb Porzio %!s(int64=3) %!d(string=hai) anos
pai
achega
de1921d691

+ 2 - 0
packages/alpinejs/src/directives/x-for.js

@@ -45,6 +45,8 @@ function loop(el, iteratorNames, evaluateItems, evaluateKey) {
             items = Array.from(Array(items).keys(), i => i + 1)
         }
 
+        if (items === undefined) items = []
+
         let lookup = el._x_lookup
         let prevKeys = el._x_prevKeys
         let scopes = []

+ 16 - 1
tests/cypress/integration/directives/x-for.spec.js

@@ -393,7 +393,6 @@ test('x-for over range using i in property syntax',
     ({ get }) => get('span').should(haveLength('10'))
 )
 
-// @flaky
 test.retry(2)('x-for with an array of numbers',
     `
         <div x-data="{ items: [] }">
@@ -412,3 +411,19 @@ test.retry(2)('x-for with an array of numbers',
         get('span').should(haveLength('2'))
     }
 )
+
+test('x-for works with undefined',
+    `
+        <div x-data="{ items: undefined }">
+            <template x-for="i in items">
+                <span x-text="i"></span>
+            </template>
+            <button @click="items.push(2)" id="first">click me</button>
+        </div>
+    `,
+    ({ get }) => {
+        get('span').should(haveLength('0'))
+        get('#first').click()
+        get('span').should(haveLength('1'))
+    }
+)