I need to have a default value in my autocomplete in my react app. My problem is when i try to submit it, it still is invalid. Meaning it has no value in it. I need to click the autocomplete and select it again just to make to have the value.
Pls check this codesandbox link CLICK HERE
<Autocomplete
name="member_status"
value={values.member_status}
options={memberStatuses ? memberStatuses : []}
getOptionLabel={(memberStatus) => memberStatus.name}
onChange={(e, value) => {
setFieldValue(
"member_status",
value !== null ? value.id : ""
);
}}
renderInput={(params) => (
<TextField
{...params}
label="Member Status"
name="member_status"
variant="outlined"
onBlur={handleBlur}
helperText={
touched.member_status ? errors.member_status : ""
}
error={
touched.member_status && Boolean(errors.member_status)
}
/>
)}
/>
The issue here is you are setting the initial value of your Autocomplete
as an object
, then you're validating for a string
.
Changing your validationSchema
to
const validationSchema = yup.object().shape({
member_status: yup
.object()
.shape({
id: yup.number(),
name: yup.string()
})
.nullable()
.required("Select member status")
});
and your Autocomplete
's onChange
handler to
...
onChange={(e, value) => {
setFieldValue("member_status", value); // set the new value to an object, not string
}}
should work.