preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.78k stars 93 forks source link

Object chain seems too long in Signals and object structuring does not work #328

Closed jaydenintusurg closed 1 year ago

jaydenintusurg commented 1 year ago

Hi, I notice that updating a nested object in Signals can be quite lengthy and object destructuring does not seem to work.

For example,

const globalStore = signal({
  student: {
    name: 'John Doe',
    id: 0,
  }
});

Every time I need to access the student name, I need to specify globalStore.value.student.name. I can't do object destructuring like const { student } = globalStore.value;

Am I missing something or is this by design how Signals is supposed to work?


const Box = () => {
  // const { student } = globalStore.value; 
  // const nameCode = useComputed(() => `${student.name} ${student.id}`); <--- Doesn't work, UI won't update when clicked
  const nameCode = useComputed(() => `${globalStore.value.student.name} ${globalStore.value.student.id}`);

  const handler = () => {
    globalStore.value = {
      ...globalStore.value,
      student: {
        ...globalStore.value.student,
        id: globalStore.value.student.id + 1,
      }
    }
  };

  return (
    <div className='box-container'>
      <div>
        Name: {globalStore.value.student.name}
      </div>
      <div>
        Name Code: {nameCode}
      </div>
      <button onClick={handler}>
        Increment code
      </button>
    </div>
  );
};
rschristian commented 1 year ago

Indeed, this is an intentional limitation in pretty much every implementation of signals.

student, once extracted, is not a signal. useComputed will not react to non-signals.