Home > OS >  How do I simply mutate the array inside a signal
How do I simply mutate the array inside a signal

Time:04-22

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'))

CodePudding user response:

The Solid tutorial strongly recommends immutability:

Solid strongly recommends the use of shallow immutable patterns for updating state. By separating reads and writes we maintain better control over the reactivity of our system without the risk of losing track of changes to our proxy when passed through layers of components.

An immutable way to accomplish what you're going for might look something like this:

setA(a => ['hello', ...a])

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 setting equals to false:

let [a, setA] = createSignal([], { equals: false });

Or you can pass a function that takes the previous and next values of the signal and returns a boolean:

let [a, setA] = createSignal([], { equals: (prev, next) => {
  if (/* dependents should run */) {
    return false;
  }
  // dependents shouldn't run
  return true;
} });
  • Related