Skip to content

Commit

Permalink
fix(useCombobox): fix onSelectedItemChange not triggering with contro…
Browse files Browse the repository at this point in the history
…lled selectedItem in React.StrictMode (#1107)

* fix(useCombobox): fix onSelectedItemChange not triggering with controlled selectedItem in React.StrictMode

* add test for useCombobox.onSelectedItemChange with controlled selectedItem in strict mode
  • Loading branch information
IwalkAlone committed Jul 8, 2020
1 parent 65d2f11 commit 5353265
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
18 changes: 18 additions & 0 deletions src/hooks/useCombobox/__tests__/props.test.js
@@ -1,3 +1,4 @@
import React from 'react'
import {renderHook, act as hooksAct} from '@testing-library/react-hooks'
import {act} from '@testing-library/react'
import {renderCombobox, renderUseCombobox} from '../testUtils'
Expand Down Expand Up @@ -952,6 +953,23 @@ describe('props', () => {
expect(input).toHaveValue(items[selectionIndex])
})

test('works correctly with the corresponding control prop in strict mode', () => {
const onSelectedItemChange = jest.fn()
const itemIndex = 0
const {clickOnItemAtIndex} = renderCombobox(
{selectedItem: null, initialIsOpen: true, onSelectedItemChange},
ui => <React.StrictMode>{ui}</React.StrictMode>,
)

clickOnItemAtIndex(itemIndex)

expect(onSelectedItemChange).toHaveBeenCalledWith(
expect.objectContaining({
selectedItem: items[itemIndex],
}),
)
})

test('can have downshift actions executed', () => {
const {result} = renderUseCombobox({
initialIsOpen: true,
Expand Down
28 changes: 15 additions & 13 deletions src/hooks/useCombobox/utils.js
@@ -1,4 +1,4 @@
import {useRef} from 'react'
import {useRef, useEffect} from 'react'
import PropTypes from 'prop-types'
import {
generateId,
Expand Down Expand Up @@ -102,19 +102,21 @@ export function useControlledReducer(reducer, initialState, props) {
const [state, dispatch] = useEnhancedReducer(reducer, initialState, props)

// ToDo: if needed, make same approach as selectedItemChanged from Downshift.
if (isControlledProp(props, 'selectedItem')) {
if (previousSelectedItemRef.current !== props.selectedItem) {
dispatch({
type: ControlledPropUpdatedSelectedItem,
inputValue: props.itemToString(props.selectedItem),
})
}
useEffect(() => {
if (isControlledProp(props, 'selectedItem')) {
if (previousSelectedItemRef.current !== props.selectedItem) {
dispatch({
type: ControlledPropUpdatedSelectedItem,
inputValue: props.itemToString(props.selectedItem),
})
}

previousSelectedItemRef.current =
state.selectedItem === previousSelectedItemRef.current
? props.selectedItem
: state.selectedItem
}
previousSelectedItemRef.current =
state.selectedItem === previousSelectedItemRef.current
? props.selectedItem
: state.selectedItem
}
})

return [getState(state, props), dispatch]
}
Expand Down

0 comments on commit 5353265

Please sign in to comment.