Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Autocomplete): make inputValue update on data prop changes #3581

Merged
merged 11 commits into from
Jun 14, 2024
28 changes: 27 additions & 1 deletion packages/dnb-eufemia/src/components/autocomplete/Autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
parseContentTitle,
getCurrentData,
getCurrentIndex,
normalizeData,
} from '../../fragments/drawer-list/DrawerListHelpers'

export default class Autocomplete extends React.PureComponent {
Expand Down Expand Up @@ -346,7 +347,6 @@ export default class Autocomplete extends React.PureComponent {

this._id = props.id || makeUniqueId()
}

render() {
return (
<DrawerListProvider
Expand Down Expand Up @@ -410,6 +410,32 @@ class AutocompleteInstance extends React.PureComponent {
state.inputValue = props.input_value
}

if (props?.data?.length > 0 && state?.prevData?.length === 0) {
let selectedItem = state.selected_item

if (props.default_value) {
selectedItem = props.default_value
}

if (
!props.default_value &&
props.value &&
props.value !== 'initval'
) {
selectedItem = props.value
}

const currentData = getCurrentData(
selectedItem,
normalizeData(props.data)
)

state.inputValue = parseContentTitle(currentData, {
separator: ' ',
preferSelectedValue: true,
})
}

if (props.data !== state.prevData) {
state.updateData(props.data)
state.prevData = props.data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1508,6 +1508,37 @@ describe('Autocomplete component', () => {
expect(input.value).toBe('Kontonummer: 987654321')
})

it('should update input value when data prop goes from emtpy to unempty and value is given', async () => {
const { rerender } = render(<Autocomplete {...mockProps} data={[]} />)

const input = document.querySelector('.dnb-input__input')

expect(input).not.toHaveValue()

rerender(
<Autocomplete
{...mockProps}
value={1}
data={[
{
selected_value: 'Bedriftskonto',
content: 'Bedriftskonto',
},
{
selected_value: 'Sparekonto',
content: 'Sparekonto',
},
{
selected_value: 'Felleskonto',
content: 'Felleskonto',
},
]}
/>
)

expect(input).toHaveValue('Sparekonto')
})

describe('should have correct values on input blur', () => {
it('when no selection is made and "keep_value" and "keep_value_and_selection" is false', async () => {
const on_change = jest.fn()
Expand Down
Loading