pacocoursey / cmdk

Fast, unstyled command menu React component.
https://cmdk.paco.me
MIT License
9.98k stars 287 forks source link

`onValueChange` is not firing #305

Closed zilahir closed 2 months ago

zilahir commented 2 months ago

The onValueChange on the Command.Dialog does not seem to be firing on the latest version (1.0.0)

function TodoSearchMenu(): ReactElement {
  const ref = useRef<HTMLDivElement | null>(null);
  const listRef = useRef<HTMLDivElement | null>(null);
  const inputRef = useRef<HTMLInputElement | null>(null);

  const { isSearchOpen: open, setSearchOpen: toggle } = useCmdkStore();

  const { data, isLoading } = useData();
  const [isSubMenuOpen, toggleSubMenu] = useState(false);

  useEffect(() => {
    const keyDown = (event: globalThis.KeyboardEvent): void => {
      if (event.key === "/") {
        event.preventDefault();
        toggle();
      }

      if (event.key === "Escape" && open) {
        event.preventDefault();
        toggle();
      }
    };

    document.addEventListener("keydown", keyDown);
    return () => document.removeEventListener("keydown", keyDown);
  }, [open, toggle]);

  const [value, setValue] = useState<string>("1");

  const navigate = useNavigate();

  function goToTodo(todoId: number): void {
    navigate(`/todo/${todoId}`);
    toggle();
  }

  return (
    <Command.Dialog
      defaultValue="1"
      open={open}
      ref={ref}
      onValueChange={(v) => setValue(v)} // <-- this
    >
      <Command.Input ref={inputRef} placeholder="Search for a todo" />
      <Command.List ref={listRef}>
        {isLoading && <Command.Loading>Fetching words…</Command.Loading>}
        <Command.Group heading={value}> // <-- does not updates, its stuck on 1
            {data?.data &&
              data?.data.length > 0 &&
              data.data.map((todo) => (
                <Command.Item
                  onSelect={(): void => goToTodo(todo.id)}
                  key={todo.id}
                  value={todo.id.toString()}
                >
                  {todo.id}
                </Command.Item>
              ))}
            )
        </Command.Group>
      </Command.List>
      <div cmdk-todosearch-footer="">
        <button type="button" cmdk-todosearch-open-trigger="">
          Open Application
          <kbd>↵</kbd>
        </button>
        <hr />
        <SubCommand
          listRef={listRef}
          selectedValue={value}
          inputRef={inputRef}
          open={isSubMenuOpen}
          setOpen={toggleSubMenu}
        />
      </div>
    </Command.Dialog>
  );
}

update:

providing the value explicitly to the Dialog solved the issue.


      onValueChange={(v) => setValue(v)}
      value={value}