|
5 | 5 | useFieldControllerWithOptionsLabels, |
6 | 6 | useOnErrorMessage, |
7 | 7 | } from '../hooks/index'; |
8 | | -import { useController } from 'react-hook-form'; |
| 8 | +import { useController, useWatch } from 'react-hook-form'; |
9 | 9 | import { useEffect, useState } from 'react'; |
10 | 10 | import type { |
11 | 11 | AsyncFieldControllerProps, |
@@ -88,32 +88,38 @@ export const AutocompleteController = < |
88 | 88 | > | null>(initialValue ?? null); |
89 | 89 |
|
90 | 90 | const { |
91 | | - field: { onChange, value, ...other }, |
| 91 | + field: { onChange, ...rest }, |
92 | 92 | fieldState: { invalid, error }, |
93 | 93 | } = useController({ |
94 | 94 | control, |
95 | 95 | name, |
96 | 96 | }); |
97 | 97 |
|
| 98 | + const formValue = useWatch({ |
| 99 | + control, |
| 100 | + name, |
| 101 | + }); |
| 102 | + |
98 | 103 | /** |
99 | 104 | * Side effects |
100 | 105 | */ |
101 | 106 | useEffect(() => { |
102 | | - if (value) { |
103 | | - const optionFound = options.find((option) => optionValueAccessor(option) === value); |
| 107 | + if (formValue) { |
| 108 | + const optionFound = options.find((option) => optionValueAccessor(option) === formValue); |
104 | 109 |
|
105 | 110 | if (optionFound) { |
106 | 111 | setSelectedValue(optionFound as AutocompleteValue<Value, Multiple, DisableClearable, FreeSolo> | null); |
| 112 | + onChange(optionValueAccessor(optionFound)); |
107 | 113 | } |
108 | 114 | } |
109 | | - }, [value, optionValueAccessor, options]); |
| 115 | + }, [formValue, optionValueAccessor, options]); |
110 | 116 |
|
111 | 117 | /** |
112 | 118 | * Render |
113 | 119 | */ |
114 | 120 | return ( |
115 | 121 | <Autocomplete |
116 | | - {...other} |
| 122 | + {...rest} |
117 | 123 | aria-required={optional ? 'false' : 'true'} |
118 | 124 | getOptionLabel={(value) => { |
119 | 125 | if (!value) { |
|
0 commit comments