S
SolidJS16mo ago
Revxrsal

make object no longer reactive

o/ so i have this piece of code
// routines: []
setRoutines(v => [...v, routine])
// routines: [{name: "..."}]
setRoutine(createEmptyRoutine())
// routines: [{name: ""}]
// routines: []
setRoutines(v => [...v, routine])
// routines: [{name: "..."}]
setRoutine(createEmptyRoutine())
// routines: [{name: ""}]
where both routines, setRoutines and routine, setRoutine are stores. since routines now contains a routine object which is in a store, further updating it in other places of the code will automatically update it in routines. is there any way to break reactivity apart, or should i just clone routine when adding it?
7 Replies
Revxrsal
RevxrsalOP16mo ago
i found out that doing
setRoutines(v => [...v, {...routine}])
setRoutines(v => [...v, {...routine}])
instead of
setRoutines(v => [...v, routine])
setRoutines(v => [...v, routine])
seems to get the job done, but is that a good approach?
Alex Lohr
Alex Lohr16mo ago
There's untrack to make things explicit.
Revxrsal
RevxrsalOP16mo ago
oh nice, but routine is a store it requires an Accessor do i () => routine?
Alex Lohr
Alex Lohr16mo ago
Exactly.
Revxrsal
RevxrsalOP16mo ago
oh okay, thanks!
Alex Lohr
Alex Lohr16mo ago
Happy to help.
bigmistqke
bigmistqke16mo ago
if i understand ur question correctly, when you do have a routines-store of value [routine] and you do setRoutine('key', 'some_value'), you do not want routines[0].key to also update to that value? When you do setRoutines(v => [...v, routine]) you actually pass that reference of routine. It's very similar like in vanilla js: routines = [...routines, routine]. What you did will work as long as routine is only of 1 level deep, but if routine is for example: {user: {id: 'name'}} the reference to {id: 'name'} will still be intact. untrack will make it that something like createEffect(() => untrack(() => store.value)) will not re-run whenever store.value changes, but it won't make a deep-copy of the values. If your data has multiple layers and you want to make an all new reference, you would need to deep-copy it somehow, structuredClone or some other way.
Want results from more Discord servers?
Add your server