File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
packages/svelte/tests/runtime-runes/samples/array-sort-in-effect Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ import { flushSync } from 'svelte' ;
2+ import { test } from '../../test' ;
3+
4+ export default test ( {
5+ /**
6+ * Ensure that sorting an array inside an $effect works correctly
7+ * and re-runs when the array changes (e.g., when items are added).
8+ */
9+ test ( { assert, target } ) {
10+ const button = target . querySelector ( 'button' ) ;
11+
12+ // initial render — array should be sorted
13+ assert . htmlEqual (
14+ target . innerHTML ,
15+ `
16+ <button>add item</button>
17+ <p>0</p>
18+ <p>50</p>
19+ <p>100</p>
20+ `
21+ ) ;
22+
23+ // add first item (20); effect should re-run and sort the array
24+ flushSync ( ( ) => button ?. click ( ) ) ;
25+
26+ assert . htmlEqual (
27+ target . innerHTML ,
28+ `
29+ <button>add item</button>
30+ <p>0</p>
31+ <p>20</p>
32+ <p>50</p>
33+ <p>100</p>
34+ `
35+ ) ;
36+
37+ // add second item (80); effect should re-run and sort the array
38+ flushSync ( ( ) => button ?. click ( ) ) ;
39+
40+ assert . htmlEqual (
41+ target . innerHTML ,
42+ `
43+ <button>add item</button>
44+ <p>0</p>
45+ <p>20</p>
46+ <p>50</p>
47+ <p>80</p>
48+ <p>100</p>
49+ `
50+ ) ;
51+ }
52+ } ) ;
Original file line number Diff line number Diff line change 1+ <script >
2+ let arr = $state ([100 , 0 , 50 ]);
3+ let nextValues = [20 , 80 ];
4+ let valueIndex = 0 ;
5+
6+ $effect (() => {
7+ arr .sort ((a , b ) => a - b);
8+ });
9+
10+ function addItem () {
11+ if (valueIndex < nextValues .length ) {
12+ arr .push (nextValues[valueIndex]);
13+ valueIndex++ ;
14+ }
15+ }
16+ </script >
17+
18+ <button onclick ={addItem }>add item</button >
19+ {#each arr as x }
20+ <p >{x }</p >
21+ {/each }
You can’t perform that action at this time.
0 commit comments