React Hook Form V7 - Material UI 5 Autocomplete: Lazy loaded values not validated

Viewed 4987

I use react-hook-form V7 with an Material UI 5 Autocomplete input. My lazy loaded values in the Autocomplete are not validated on first submit click (but on second). What's wrong?


  useEffect(() => {
    setItemList([
      { id: 1, name: "item1" },
      { id: 2, name: "item2" }
    ]);
    setItemIdSelected(2);
  }, []);

  [...]

  <Autocomplete
    options={itemList}
    getOptionLabel={(item) => (item.name ? item.name : "")}
    getOptionSelected={(option, value) =>
      value === undefined || value === "" || option.id === value.id
    }
    value={
      itemIdSelected
        ? itemList.find((item) => item.id === itemIdSelected)
        : ""
    }
    onChange={(event, items) => {
      if (items !== null) {
        setItemIdSelected(items.id);
      }
    }}
    renderInput={(params) => (
      <TextField
        {...params}
        {...itemsIdFormHookRest}
        label="items"
        margin="normal"
        variant="outlined"
        inputRef={itemsIdFormHookRef}
        error={errors.itemsId ? true : false}
        helperText={errors.itemsId && "item required"}
        required
      />
    )}
  />
  
[...]

Please have a look to the code on code sandbox:

Edit React Hook Form V7 - Material UI 5 - lazy loaded values not validated in Autocomplete

3 Answers

You should wrap the Material UI Autocomplete with the Controller Component provided by React Hook Form. See this section in the documentation for further information.

I would also suggest to remove the useState saving the id, as you could also access the value via React Hook Form either through getValues or after the handleSubmit callback is called.

Here is the updated CodeSandbox.

How can i implement datepickers? This works only with modal, but when typing yourself is not working.

<LocalizationProvider dateAdapter={AdapterDateFns} locale={ruLocale}>
  <Controller
    render={({ field }) => (
      <DatePicker
        value={field.value}
        onChange={(value) => field.onChange(value)}
        renderInput={(params) => (
          <TextField {...params} />
        )}
      />
    )}
    name={name}
    control={control}
  />
</LocalizationProvider>

I handle react-hook-form with mui Autocomplete in the following way

"devDependencies": {
    "@mui/material": "^5.8.3",
    "react-hook-form": "^7.33.1",
}
const Country = [{ label: 'United Kingdem', value: 'uk' }];

<Controller
    name={"country"}
    control={control}
    rules={{
        required: true,
    }}
    render={({ field: { onChange, ..._field } }) => (
        <Autocomplete
            options={Country}
            onChange={(_, data) => onChange(data.value)}
            renderInput={(params) => {
                return (
                    <TextField
                        {...params}
                        label="disableCloseOnSelect"
                        variant="standard"
                    />
                );
            }}
            {..._field}
        />
    )}
/>
Related