Skip to content

this is not bound to state #1004

Answered by dai-shi
bisubus asked this question in Q&A
Dec 8, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

Is there a reason why this was made so in valtio

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;
};

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@bisubus
Comment options

Answer selected by bisubus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants