Skip to content

Svelte 5: Sorting an array from props is unreactive #13446

@jameshulse

Description

@jameshulse

Describe the bug

If a component receives an array, it cannot directly sort by a dynamic key to some $derived state. Changing the sort key is non-reactive.

e.g. changing the value of order with changeOrder doesn't work unless we spread the items. This isn't obvious as the result of .sort(...) is a new value - so I'm not sure why the value it acts on would need to be new (and not directly using a prop).

let { items } = $props();
let order = $state(true);

// Doesn't work
// let sortedItems = $derived(items.sort((a, b) => order ? (a - b) : (b -a)))

// Works
let sortedItems = $derived([...items].sort((a, b) => order ? a.localeCompare(b) : b.localeCompare(a)))
	
function changeOrder() {
    order = !order;
}

Reproduction

https://svelte-5-preview.vercel.app/#H4sIAAAAAAAAA51STWvcMBD9K1MlIBkc--7YLiW9FAqFXnpY70ErzyZibclIs1uK0X8vo3WWNjSXHjSM5uO9pxmt4mgnjKLZrcLpGUUjPi2LKAX9WvgSLzgRilJEfw6GI200wS4Ek3bP3SAoDqIf3EB2Xnwg-GojwTH4GWRV86W6QshHLpqQwBLOETrYSS1LkAc2hs3IBuX-cXBtfWVhZNdmzDX3Jah7UYrZj_ZocRQNhTOm8iaeS_9D_SZt3cQl6OB-CX6Jqrjp9mHEwIlImlAxcU66geoaPnuMThL89OG0hbgp-kA4ftmefD9isBccVaapOKmULuFQQNdvBB9BaXjgUAPqAA-6KIobyw8fTvFV0DvYu6qqMv7-PQJdTd7oCZ_8vOiAKnMd3gQ3XuJzPDtD1jswL9o94zfGUQWsOU-vg_mQnTyv9GaF6x1q8_KXYh3zsBOXt6O99HnBqa3ZH9xac0fK-z-cibwD78xkzalb_1CR-u94wRAR1Hp7n9TRSGhAjshOKtr6CvGPr7NPvwET3CIvAwMAAA==

Logs

No response

System Info

Chrome

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions