Created
October 19, 2023 08:46
-
-
Save paprikati/82c58b025e3e7a0ce685e9e441f5970f to your computer and use it in GitHub Desktop.
react-hook-form setValue bug repro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./styles.css"; | |
import { | |
useForm, | |
FormProvider, | |
useController, | |
useFormContext | |
} from "react-hook-form"; | |
import React, { useState } from "react"; | |
import ReactAsyncSelect from "react-select/async"; | |
export default function App() { | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
<MyForm /> | |
</div> | |
); | |
} | |
type FormData = { | |
bar: SelectOption; | |
}; | |
const MyForm = () => { | |
const formMethods = useForm<FormData>({ | |
defaultValues: { bar: { label: "b", value: "b" } } | |
}); | |
const setValueOfBar = () => { | |
formMethods.setValue("bar", undefined); | |
}; | |
return ( | |
<form> | |
<FormProvider {...formMethods}> | |
<MyControlledComplexFormElement /> | |
<button onClick={setValueOfBar} type="button"> | |
Clear value | |
</button> | |
</FormProvider> | |
</form> | |
); | |
}; | |
const MyControlledComplexFormElement = () => { | |
const { watch } = useFormContext(); | |
const watchValue = watch("bar"); | |
const { field } = useController<FormData>({ name: "bar" }); | |
console.log(field.value, watchValue); | |
return ( | |
<div> | |
<AsyncSelect {...field} /> | |
<br /> | |
<div> | |
field.value: <>{JSON.stringify(field.value)}</> | |
</div> | |
<div> | |
watchValue: <>{JSON.stringify(watchValue)}</> | |
</div> | |
</div> | |
); | |
}; | |
type SelectOption = { | |
label: string; | |
value: string; | |
}; | |
export const AsyncSelect = React.forwardRef((props: any, ref) => { | |
const { | |
icon, | |
id, | |
value, | |
onChange, | |
invalid = false, | |
autoFocus, | |
...rest | |
} = props; | |
const options = [ | |
{ | |
label: "a", | |
value: "a" | |
}, | |
{ | |
label: "b", | |
value: "b" | |
}, | |
{ | |
label: "c", | |
value: "c" | |
} | |
]; | |
const loadOptions = (inputValue: string) => { | |
return Promise.resolve(options); | |
}; | |
return ( | |
<ReactAsyncSelect<SelectOption, false> | |
ref={ref} | |
value={value} | |
onChange={onChange} | |
loadOptions={loadOptions} | |
defaultOptions={true} | |
isMulti={false} | |
isClearable | |
closeMenuOnSelect | |
menuPortalTarget={document.body} | |
autoFocus={autoFocus} | |
{...rest} | |
/> | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment