How to listen to only a certain value of an object in solid-js?

Viewed 45
const App: Component = () => {
  const [obj, setObj] = createSignal({
    name: "John",
    age: 30,
  })

  createEffect(
    on(
      () => obj().name,
      (value) => {
        console.log("name", value)
      }
    )
  )
return ()=>(<button onClick={()=> setObj(obj=> ({ ...obj, age: obj.age + 1}))}>+</button>)
}

When I change age, createEffect will also be triggered, I just want to listen on name, similar to watch in Vue3.

function setup(){
  const obj = reactive({
    name: "John",
    age: 30,
  })
  watch(()=> obj.name,(value)=>{ console.log("name", value) })
}

Any good ideas?

1 Answers

SolidJS will not keep track of individual properties of a signal object.

Also you are overwriting the object every time a value changes when destructuring it (aka. {...obj, }).

If you want createEffect to keep track of your individual properties try createStore.

Here's your example written with createStore instead of createSignal

import {createStore} from 'solid-js/store'; // <- This is very important

const App: Component = () => {
  const [obj, setObj] = createStore({
    name: "John",
    age: 30,
  })

  createEffect(() => console.log(obj.name));

  return (<button onClick={setObject('age', obj.age + 1)}>+</button>)
  )
}

if you run this example, you'll see that console.log(obj.name) will only run once, this is because solid-js will keep track of individual properties when saving them on a createStore

Related