van icon indicating copy to clipboard operation
van copied to clipboard

array function push, splice doesn't trigger state change and redraw

Open kangaroolab opened this issue 1 year ago • 2 comments

let subnodes = van.state([]);
...
button({
                innerHTML: '+',
                onclick: () =>
                    {subnodes.push(key + '.' + (subnodes.length + 1))}
            }),

if I do above, it doesn't trigger any change

if I change onclick to

onclick: () =>
                    {subnodes.val = [...subnodes.val, (key + '.' + (subnodes.val.length + 1))]}

it works as expected.

same issue/behavior with subnodes.val.splice

any insight why push/splice doesn't work?

kangaroolab avatar Aug 28 '24 04:08 kangaroolab

This is intended behavior. VanJS uses reference equality check to determine whether a state has changed. If you call push or splice method, the reference to the underlying array won't change, thus won't trigger a DOM update. If you want the DOM tree to be updated on the mutation of an array, you can take a look at vanX.list in VanX extension.

Tao-VanJS avatar Aug 28 '24 05:08 Tao-VanJS

Same state behaviour as react / vue , seemingly not a bug.

VansonLeung avatar Jan 27 '25 13:01 VansonLeung