Skip to content

Commit

Permalink
fix(Forms): add Iterate support for Field.PostalCodeAndCity when usin…
Browse files Browse the repository at this point in the history
…g `country` with a path (#4215)

Fixes #4200

---------

Co-authored-by: Anders <[email protected]>
  • Loading branch information
tujoworker and langz authored Nov 5, 2024
1 parent 6b64868 commit 6f80ed9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,34 @@ describe('Field.PostalCodeAndCity', () => {
expect(postalCodeNo).toHaveAttribute('aria-placeholder', '0000')
})

it('should use value from country inside iterate', async () => {
render(
<Form.Handler
defaultData={{ items: [{ country: 'NO' }, { country: 'DE' }] }}
>
<Iterate.Array path="/items">
<Field.PostalCodeAndCity country="/country" />
</Iterate.Array>
</Form.Handler>
)

const [norway, germany] = Array.from(
document.querySelectorAll('.dnb-forms-field-postal-code-and-city')
)

await userEvent.type(
norway.querySelector('input'),
'{Backspace>4}987654'
)
expect(norway.querySelector('input').value).toBe('9876')

await userEvent.type(
germany.querySelector('input'),
'{Backspace>4}987654'
)
expect(germany.querySelector('input').value).toBe('987654')
})

describe('ARIA', () => {
const props = {
postalCode: { required: true, validateInitially: true },
Expand Down
10 changes: 8 additions & 2 deletions packages/dnb-eufemia/src/extensions/forms/hooks/useDataValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useCallback, useContext, useRef } from 'react'
import pointer from '../utils/json-pointer'
import { Path } from '../types'
import DataContext, { ContextState } from '../DataContext/Context'
import IterateItemContext from '../Iterate/IterateItemContext'
import usePath from './usePath'

export type Props<Value> = {
Expand All @@ -16,7 +17,8 @@ export default function useDataValue<Value>({
value,
}: Props<Value> = {}) {
const dataContextRef = useRef<ContextState>()
dataContextRef.current = useContext<ContextState>(DataContext)
dataContextRef.current = useContext(DataContext)
const iterateItemContext = useContext(IterateItemContext)

const { makePath, makeIteratePath } = usePath()

Expand Down Expand Up @@ -76,12 +78,16 @@ export default function useDataValue<Value>({
const getSourceValue = useCallback(
(source: Path | Value) => {
if (typeof source === 'string' && isPath(source)) {
if (iterateItemContext) {
return getValueByIteratePath(source)
}

return getValueByPath(source)
}

return source
},
[getValueByPath]
[getValueByIteratePath, getValueByPath, iterateItemContext]
)

if (pathProp) {
Expand Down

0 comments on commit 6f80ed9

Please sign in to comment.