Issue
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?
Solution
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
Answered By - Edlingao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.