Skip to content

Derive working with single derived property, but failing with two #2

Description

@dai-shi

Transferred from: pmndrs/valtio#687 by @DavidMulder0


Summary

Have a hard time describing the issue, because if I had figured out what's exactly going on I would be doing a pull request instead of a bug report, however I do have a decently clean MVE:

const createItem = (id: string, store: any): any => {
  let itemProxy = proxy({
    id
  });
  derive(
    {
      // commenting out the `isSelected` derived property magically causes the `isHovered` property to work
      isSelected: (get) => {
        return get(store).selected === get(itemProxy).id;
      },
      isHovered: (get) => {
        return get(store).hovered === get(itemProxy).id;
      }
    },
    { proxy: itemProxy }
  );
  return itemProxy;
};

const store = proxy({
  selected: (undefined as unknown) as string,
  hovered: (undefined as unknown) as string,
  byId: {} as Record<
    string,
    {
      id: string;
      readonly isHovered: boolean;
      readonly isSelected: boolean;
    }
  >
});

store.byId.a = createItem("a", store);
store.byId.b = createItem("b", store);

const nextTick = (t = 0) => new Promise((resolve) => setTimeout(resolve, t));

console.group("setting hovered to item A");
store.hovered = "a";
await nextTick();
console.log("a.isHovered", store.byId.a.isHovered); // true
console.log("b.isHovered", store.byId.b.isHovered); // false
console.groupEnd();

console.group("setting hovered to item B");
store.hovered = "b";
await nextTick();
console.log("a.isHovered", store.byId.a.isHovered); // false
console.log("b.isHovered", store.byId.b.isHovered); // false, should be true
console.groupEnd();

Link to reproduction

https://codesandbox.io/s/laughing-gates-mo58dj?file=/src/index.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions