sour-pinkS
Refine2y ago
8 replies
sour-pink

Programmatically update value of Autocomplete

Hello,

I am using useAutocomplete which is working great so far but I am trying to implement an additional scenario which involves updating the autocomplete value programmatically. The problem I am having at the moment is that the UI of the autoccomplete is not updated when I use the setValue method of the form. If I am explicitly setting the value property of the autocomplete everything works but I am wondering if there is a better way to handle this so that I do not have to add an additional state to my component.

Here is the definition of my autocomplete:

 const { autocompleteProps } = useAutocomplete<ICasinoTag>({
    resource: "casino/tags",
    dataProviderName: "api",
    debounce: 500,
    searchField: "name"
  });


<Controller
            control={control}
            name="tags"
            rules={{ required: "This field is required" }}
            render={({ field }) => {
              return (
                <Autocomplete
                  {...autocompleteProps}
                  multiple
                  onChange={(_, value) => {
                    field.onChange(value);
                  }}
                  sx={{ width: '100%' }}
                  getOptionLabel={tag => tag.name}
                  isOptionEqualToValue={(option, value) =>
                    value === undefined ||
                    option?.id?.toString() === (value?.id ?? value)?.toString()
                  }
                  renderInput={(params) => {
                    return (
                      <TextField
                        {...params}
                        label="Tags"
                        margin="normal"
                        variant="outlined"
                        error={!!errors.tags}

                        required
                        placeholder="Select tags"
                      />
                    );
                  }
                  }
                />
              );
            }
            }
          />
Was this page helpful?