This is a working example, with a problem. I want to splice an existing array inside a signal, and return it to see it updated. But it doesn't work. How do I simply mutate the array inside a signal? I don't want to create new arrays just a simple splice. There is no example in the docs about mutating an array.
import { render } from 'solid-js/web';
import { createSignal, createEffect } from 'solid-js'
function HelloWorld() {
let [a, setA] = createSignal([])
setTimeout(() =>
setA(a => {
a.splice(0, 0, 'hello')
// this logs as requested if I uncomment this
//return ['hello']
return a
}))
createEffect(() => {
console.log(a())
})
return <div>Hello World!</div>;
}
render(() => <HelloWorld />, document.getElementById('app'))
The Solid tutorial strongly recommends immutability:
An immutable way to accomplish what you're going for might look something like this:
If, however, you determine you must mutate the signal, you can specify a how Solid determines if a signal has been updated within
createSignal
's options object. By default, signal changes are compared by referential equality using the===
operator. You can tell Solid to always re-run dependents after the setter is called by settingequals
tofalse
:Or you can pass a function that takes the
previous
andnext
values of the signal and returns aboolean
: