Store with const obj values passed to it does not update.

const initialViewable = {
itemSource: true,
itemCategory: true,
itemType: true,
inSearch: false,
noFound: false,
};

const [viewable, setViewable] = createStore(initialViewable);

setViewable(initialViewable); // this does not work

setViewable({
itemSource: true,
itemCategory: true,
itemType: true,
inSearch: false,
noFound: false,
}); // this does
const initialViewable = {
itemSource: true,
itemCategory: true,
itemType: true,
inSearch: false,
noFound: false,
};

const [viewable, setViewable] = createStore(initialViewable);

setViewable(initialViewable); // this does not work

setViewable({
itemSource: true,
itemCategory: true,
itemType: true,
inSearch: false,
noFound: false,
}); // this does
Once a condition is met, I need to reset my component. I thought of doing this by using the initial values I used to instantiate a store. However, if I pass the constant directly, it doesn't work, but if I pass an object manually, it does. Why is that?
7 Replies
mrVinicius
mrViniciusOP2mo ago
This problem only seem to occur with the initialViewable, a new const obj does work I feel its javascript memory layout or solid compiler to blame
REEEEE
REEEEE2mo ago
It's the same object as the one you passed in that's why, you need to spread the object
mrVinicius
mrViniciusOP2mo ago
how?
setViewable(...initialViewable ) // is invalid
setViewable(() => ({...initialViewable })) // doesnt do anything
setViewable((prev) => ({...prev, ...initialViewable })) // doesnt do anything
setViewable(...initialViewable ) // is invalid
setViewable(() => ({...initialViewable })) // doesnt do anything
setViewable((prev) => ({...prev, ...initialViewable })) // doesnt do anything
REEEEE
REEEEE2mo ago
setViewable({...initialViewable}) I meant the original store tho createStore({...initialViewable})
mrVinicius
mrViniciusOP2mo ago
Oh thanks, didn't thought of this approach, worked like a charm
Andreas Roth
Andreas Roth2mo ago
Maybe to give an explanation: Internally, solid.js like to mutate things. By only updating instead of re-creating solid can achieve its finegrained reactivity. In your case, your initial object is mutated by solid as it's passed as the initial state to createStore. Thus, after you changed your UI, initialViewable is also changed. By creating a new object that you pass to createStore, the original object stays unchanged and can be used to properly reset.
mrVinicius
mrViniciusOP2mo ago
Oh, that make sense, thanks for the input!
Want results from more Discord servers?
Add your server