Answer a question

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

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.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐