-
Regarding this section of the docs:
I expected there could be performance and other benefits from accessing a different context (snapshot) as state.inc() // `this` points to `state` and it works fine
const snap = useSnapshot(state)
snap.inc() // `this` points to `snap` and it doesn't work because snapshot is frozen But this won't happen when
I previously dealt with pinia where "this" is bound to store context. It makes sense there because (a) store instance doesn't exist at the time when functions are defined and cannot be directly referred as a var, (b) makes it easy to destructure methods from a store (c) functions are wrapped anyway to be integrated with store debugging and other magic, so why not bind them too Is there a reason why this was made so in valtio besides the simplicity of the implementation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Because it's how JS works. Valtio's design policy is to be transparent, so it tries to make these two equivalent as much as possible. const state1 = proxy({ ... });
const state2 = { ... }; If we need to bind, we need to do it explicitly. state.inc = state.inc.bind(state); One can create a wrapper util if they want. const proxyWithBindindMethods = (initialObj) => {
const state = proxy(initialObj);
for (const key of state) {
if (typeof state[key] === 'function') {
state[key] = state[key].bind(state);
}
}
return state;
}; |
Beta Was this translation helpful? Give feedback.
Because it's how JS works. Valtio's design policy is to be transparent, so it tries to make these two equivalent as much as possible.
If we need to bind, we need to do it explicitly.
One can create a wrapper util if they want.