How to wrap a store without losing reactivity

Given a store like this:
const [store setStore] = createStore({
users: [
{ firstName: 'William', lastName: 'Shakespeare' },
{ firstName: 'Charles', lastName: 'Darwin' }
]
})
const [store setStore] = createStore({
users: [
{ firstName: 'William', lastName: 'Shakespeare' },
{ firstName: 'Charles', lastName: 'Darwin' }
]
})
How can I do the following without losing reactivity?
const userWrapper = {
...store[0],
get fullName() {
return store[0].firstName + store[0].lastName;
}
}
const userWrapper = {
...store[0],
get fullName() {
return store[0].firstName + store[0].lastName;
}
}
9 Replies
REEEEE
REEEEE4mo ago
make userWrapper a function
João Bezerra
João BezerraOP4mo ago
Isn't there a way to do this with userWrapper being a proxy?
Katja (katywings)
You could indeed use a real proxy for userWrapper, like:
new Proxy({}, {
get(target, prop, receiver) {
if (prop === "fullName") {
return store[0].firstName + store[0].lastName;
}
return store[0][prop];
},
});
new Proxy({}, {
get(target, prop, receiver) {
if (prop === "fullName") {
return store[0].firstName + store[0].lastName;
}
return store[0][prop];
},
});
P.S. this example is incomplete and would need additional code if the proxy has to feel like a real object.
João Bezerra
João BezerraOP4mo ago
Interesting. Can you clarify what you mean by "feel like a real object"?
Katja (katywings)
The proxy handler would have to include things like ownKeys, has and stuff like that, otherwise Object.keys(theProxy) would return the wrong thing
mdynnl
mdynnl4mo ago
There's a builtin helper for cases like this 😁 but the original use case was for something fundamental. 🥁 🥁 🥁
mergeProps(() => store[0], { // this needs to be an accessor, but don't have to if you're just using wrapping `store`
get fullName() {
...
}
})
mergeProps(() => store[0], { // this needs to be an accessor, but don't have to if you're just using wrapping `store`
get fullName() {
...
}
})
Katja (katywings)
Clever, i never had the idea to use mergeProps like this 😆
mdynnl
mdynnl4mo ago
Yeah, it's the same trick https://playground.solidjs.com/anonymous/2505074a-ab78-42e9-af76-6537ebd107a4 (check output tab) It's the reactivity's equivalent of js native spread
João Bezerra
João BezerraOP4mo ago
I was gonna say it would be cool if there was an utility for this. Also didn't know mergeProps could be used here. Nice! I guess this answers my question 🙂
Want results from more Discord servers?
Add your server