diff --git a/src/autocomplete/__tests__/Autocomplete.test.js b/src/autocomplete/__tests__/Autocomplete.test.js index e4673994e..5399ce113 100644 --- a/src/autocomplete/__tests__/Autocomplete.test.js +++ b/src/autocomplete/__tests__/Autocomplete.test.js @@ -84,5 +84,32 @@ describe('Autocomplete', () => { expect(textInput).toHaveValue('A') }) }) + + describe('when inputvalues is object', () => { + it.only('should read data autocomplete', async () => { + const items = [{name: 'Apple', id: 1}, {name: 'Orange', id: 2}] + + render( + makeAutocompleteFixture({ + allowOtherValues: true, + items, + itemToString: (item) => (item ? item.name : ""), + }) + ) + + // Type 'A' into the input to filter items down containing the string + const textInput = await screen.findByTestId('TextInput') + userEvent.click(textInput) + userEvent.type(textInput, 'A') + + // Click the 'Apple' option, which should also update the input element + const item = await screen.findByText('Apple') + userEvent.click(item) + + + // an object will be returned in the input without error + expect(textInput).toHaveValue('Apple') + }) + }); }) }) diff --git a/src/autocomplete/src/Autocomplete.js b/src/autocomplete/src/Autocomplete.js index e9fb47dd4..ef4ff6575 100644 --- a/src/autocomplete/src/Autocomplete.js +++ b/src/autocomplete/src/Autocomplete.js @@ -2,7 +2,7 @@ import React, { memo, forwardRef, useState, useEffect, useCallback } from 'react import VirtualList from '@segment/react-tiny-virtual-list' import Downshift from 'downshift' import fuzzaldrin from 'fuzzaldrin-plus' -import PropTypes from 'prop-types' +import PropTypes, { string } from 'prop-types' import { Position } from '../../constants' import { Pane } from '../../layers' import { Popover } from '../../popover' @@ -46,7 +46,7 @@ const AutocompleteItems = ({ width }) => { itemsFilter = itemsFilter || fuzzyFilter(itemToString) - const items = isFilterDisabled || inputValue.trim() === '' ? originalItems : itemsFilter(originalItems, inputValue) + const items = isFilterDisabled || (typeof inputValue === 'string' && inputValue.trim() === '') ? originalItems : itemsFilter(originalItems, inputValue) if (items.length <= 0) return null @@ -128,11 +128,8 @@ const Autocomplete = memo( } if (props.allowOtherValues && state.isOpen && !changes.isOpen) { - return { - ...changes, - selectedItem: changes.selectedItem || state.inputValue, - inputValue: changes.selectedItem || state.inputValue - } + const valueItem = changes.selectedItem || state.inputValue; + return typeof valueItem === 'object' ? {...changes, selectedItem: valueItem} : {...changes, selectedItem: valueItem, inputValue: valueItem} } return changes