Skip to content

Commit

Permalink
Fix controlled item value (#109)
Browse files Browse the repository at this point in the history
* fix: keep item value controlled

* test: add keep controlled value test

---------

Co-authored-by: Paco <34928425+pacocoursey@users.noreply.github.com>
joaom00 and pacocoursey authored Apr 10, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent f78222b commit 65168c2
Showing 2 changed files with 11 additions and 1 deletion.
3 changes: 2 additions & 1 deletion cmdk/src/index.tsx
Original file line number Diff line number Diff line change
@@ -182,7 +182,8 @@ const Command = React.forwardRef<HTMLDivElement, CommandProps>((props, forwarded
} else if (key === 'value') {
if (propsRef.current?.value !== undefined) {
// If controlled, just call the callback instead of updating state internally
propsRef.current.onValueChange?.(value as string)
const newValue = (value ?? '') as string
propsRef.current.onValueChange?.(newValue)
return
// opts is a boolean referring to whether it should NOT be scrolled into view
} else if (!opts) {
9 changes: 9 additions & 0 deletions test/props.test.ts
Original file line number Diff line number Diff line change
@@ -21,6 +21,15 @@ test.describe('props', async () => {
await expect(page.locator(`[cmdk-item][aria-selected]`)).toHaveAttribute('data-value', 'anteater')
})

test('keep controlled value if empty results', async ({ page }) => {
await page.goto('/props')
await expect(page.locator(`[data-testid=value]`)).toHaveText('ant')
await page.locator(`[cmdk-input]`).fill('d')
await expect(page.locator(`[data-testid=value]`)).toHaveText('')
await page.locator(`[cmdk-input]`).fill('ant')
await expect(page.locator(`[data-testid=value]`)).toHaveText('ant')
})

test('controlled search', async ({ page }) => {
await page.goto('/props')
await expect(page.locator(`[cmdk-item][aria-selected]`)).toHaveAttribute('data-value', 'ant')

1 comment on commit 65168c2

@vercel
Copy link

@vercel vercel bot commented on 65168c2 Apr 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

cmdk-website – ./

cmdk.vercel.app
cmdk-website-paco.vercel.app
cmdk-website-git-main-paco.vercel.app
cmdk.paco.me

Please sign in to comment.