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(Forms): ensure setFieldStatus by useValidation does not throw when used without id #4529

Merged
merged 1 commit into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ describe('useValidation', () => {
})

describe('setFieldStatus', () => {
it('should not throw when no id is given', () => {
const { result } = renderHook(useValidation)
result.current.setFieldStatus('/path', { error: null })
})

describe('with an identifier', () => {
it('should set and remove a field error', async () => {
const onSubmit = jest.fn()
Expand Down Expand Up @@ -469,6 +474,43 @@ describe('useValidation', () => {
expect(info).toHaveTextContent('Show me again')
})
})

it('should handle the setFormError method outside of the form context', async () => {
const myId = () => null
const onSubmit = jest.fn()

const MockComponent = () => {
const { setFieldStatus } = useValidation(myId)

return (
<Form.Handler id={myId} onSubmit={onSubmit}>
<Field.String
label="My field"
path="/myField"
onChange={(value) => {
if (value === 'error') {
setFieldStatus('/myField', {
error: new Error('Error message'),
})
}
}}
/>
</Form.Handler>
)
}

render(<MockComponent />)

await userEvent.type(document.querySelector('input'), 'error')

fireEvent.submit(document.querySelector('form'))

expect(onSubmit).toHaveBeenCalledTimes(0)

expect(
document.querySelector('.dnb-form-status')
).toBeInTheDocument()
})
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function useConnections(id: SharedStateId = undefined) {
const connections =
attachments?.fieldConnectionsRef || (!id && fieldConnectionsRef)

return connections.current
return connections?.current
}, [fieldConnectionsRef, get, id])

return useMemo(() => ({ getFieldConnections }), [getFieldConnections])
Expand Down
Loading