Error in typescript Autocomplete component from @mui/material

Currently, I am working on implementing an Autocomplete field using react-hook-form. Everything seems to be functioning correctly, but I have encountered a TypeScript error:

The provided object does not match the expected type 'AutocompleteProps<{ value: MeasuringSystem; label: string; }, undefined, true, undefined, "div">'.
  The 'value' property types are incompatible.
    The type 'string | { value: MeasuringSystem; label: string; }' is not assignable to type '{ value: MeasuringSystem; label: string; } | undefined'.
      The type 'string' is not assignable to type '{ value: MeasuringSystem; label: string; } | undefined'.ts(2322)

Below is the relevant code snippet:

export enum MeasuringSystem {
  Imperial = 'IMPERIAL',
  Metric = 'METRIC',
}

interface MeasuringSystemOption {
  value: MeasuringSystem;
  label: string;
}

interface DefaultValues {
  firstName: string | undefined;
  lastName: string | undefined;
  trailName: string | undefined;
  measuringSystem: MeasuringSystemOption;
  address1: string | undefined;
  address2: string | undefined;
  city: string | undefined;
  state: string | undefined;
  country: string | undefined;
}

const measuringSystemOptions = [
  { value: MeasuringSystem.Imperial, label: 'Imperial (lbs, oz)' },
  { value: MeasuringSystem.Metric, label: 'Metric (kg, g)' },
];

const Profile: React.FC = () => {
  ...other code

  const defaultSystem = measuringSystemOptions.find(
    opt => opt.value === currentUser?.measuringSystem
  );
  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: yupResolver(validationSchema),
    mode: 'onSubmit',
    reValidateMode: 'onBlur',
    defaultValues: {
      firstName: currentUser?.firstName ?? '',
      lastName: currentUser?.lastName ? currentUser.lastName : '',
      measuringSystem: defaultSystem || '',
      address1: currentUser?.address1 ?? '',
      address2: currentUser?.address2 ? currentUser.address2 : '',
      city: currentUser?.city ? currentUser.city : '',
      state: currentUser?.state ? currentUser.state : '',
      country: currentUser?.country ? currentUser.country : '',
    },
  });

  useEffect(() => {
    const resetUser = {
      firstName: currentUser?.firstName ?? '',
      lastName: currentUser?.lastName ?? '',
      address1: currentUser?.address1 ?? '',
      address2: currentUser?.address2 ?? '',
      city: currentUser?.city ?? '',
      state: currentUser?.state ?? '',
      country: currentUser?.country ?? '',
      measuringSystem: defaultSystem ?? '',
    } as any;
    if (currentUser) reset(resetUser);
  }, [currentUser]);

  return (
    <div>
      <Controller
        control={control}
        name="measuringSystem"
        render={({ field }) => (
          <Autocomplete // <-- TS Error
            {...field}
            autoComplete
            disableClearable
            fullWidth
            options={measuringSystemOptions}
            onChange={(e, v) => field.onChange(v)}
            isOptionEqualToValue={(option, value) =>
              option.value === value.value
            }
            renderInput={(params: AutocompleteRenderInputParams) => (
              <TextField
                {...params}
                inputRef={field.ref}
                error={!!errors?.measuringSystem}
                helperText={(errors?.measuringSystem as any)?.message}
                label="Preferred Measuring System"
                variant="outlined"
                size="small"
                InputProps={{
                  ...params.InputProps,
                  startAdornment: (
                    <InputAdornment position="start">
                      <PublicIcon
                        color={
                          errors?.measuringSystem ? 'error' : 'inherit'
                        }
                      />
                    </InputAdornment>
                  ),
                }}
              />
            )}
          />
        )}
      />  
    </div>
  );
};

I understand the nature of the error, but I am unsure how to resolve it. Any guidance on this?

Answer №1

Big shoutout to @NearHuscarl for the helpful solution shared in the post comments. Here's the code snippet that did the trick:

const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<DefaultValues>({
    resolver: yupResolver(validationSchema),
    mode: 'onSubmit',
    reValidateMode: 'onBlur',
    defaultValues: {
      firstName: currentUser?.firstName ?? '',
      lastName: currentUser?.lastName ?? '',
      trailName: currentUser?.trailName ?? '',
      measuringSystem: defaultSystem,
      address1: currentUser?.address1 ?? '',
      address2: currentUser?.address2 ?? '',
      city: currentUser?.city ?? '',
      state: currentUser?.state ?? '',
      country: currentUser?.country ?? '',
    },
  });

The key change here is that <DefaultValues> is being passed to the useForm function, and the measuringSystem is adjusted so it no longer defaults to an empty string if undefined or null. This adjustment successfully resolves all of the related issues!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Creating pagination functionality for a React Material table

Check out this Spring Boot endpoint that I use for retrieving items from the database: import React, { useEffect, useState } from "react"; // Additional imports export default function BusinessCustomersTable() { // Functionality and code impl ...

"Encountered a problem while attempting to download the .xlsx file through http.get in an angular application interfacing

Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error: https://i.sstatic.net/7pwDl.png The code snippet from my service.ts is provided below: public exportExcelFile(matchedRows: string, reportInfoId: num ...

Tips for implementing debounce functionality in mui Autocomplete

How can I debounce the onInputChange function within the MyAutocomplete component? export interface AutocompleteProps<V extends FieldValues> { onInputChange: UseAutocompleteProps<UserOrEmail, true, false, false>['onInputChange']; } ...

Exploring the functionality of generic components in React Native when using TypeScript

As an illustration, consider export class FlatList<ItemT> extends React.Component<FlatListProps<ItemT>> which incorporates the generic type ItemT. How can I utilize it in a .tsx code? When not parametrized, it appears like this: <Flat ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

I am currently utilizing MUI-Data-Tables and am seeking to customize the header text color after selecting a sorting option for the column

I am trying to find a way to change the default black text color when sorting a column, but I haven't had much success so far. The only progress I've made is changing the arrow icon color using the following code snippet. MUIDataTableHeadCell: { ...

React Hook Form: Issue with useForm not displaying any errors in formState

Currently in the process of developing an app using T3 stack along with react-hook-form and zodResolver:@hookform/resolvers/zod Below is the zod schema that I have defined: export const AccountSchema = z.object({ id: z.string().uuid().optional(), titl ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

Is it possible to replace Material UI theme with a custom JSS theme?

Currently, I am utilizing JSS themes for styling my components. However, it appears that my personalized JSS theme is conflicting with the JSS theme applied to the Material UI components. The version of material-ui being used is 1.0.0-beta.22. The setup r ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method firebase.auth().signInWithEmailAndPassword(email, password). Now, my objective is to conduct a unit test to ensure that when the myAuthenticationPlugin.authenticate(email, password) method is invoked from ...

Extracting Information from ASP.Net Web API using Angular 4

After experimenting with the well-known Visual Studio 2017 Angular 4 template, I successfully tested the functionality of side navbar buttons to retrieve in-memory data. I then proceeded to enhance the project by adding a new ASP.Net Core 2.0 API controll ...

Is it possible to obtain the URL (including parameters) of the first navigation before proceeding with the navigation process?

My goal is to automatically navigate to a specific website when a certain condition for the URL is met. Consider the following scenario in the ngOnInit() method of app.component.ts: if (urlMatchesCondition()) { await this.router.navigateByUrl('sp ...

React: Implement a feature to execute a function only after the user finishes typing

Currently, I am using react-select with an asynchronous create table and have integrated it into a Netsuite custom page. A issue I am facing is that I would like the getAsyncOptions function to only trigger when the user stops typing. The problem right now ...

Getting rid of the arrow icons in a Material UI TextField

I am facing a challenge with removing the up and down arrow icons from a Material UI TextField that I adjusted using the Material UI documentation (https://material-ui.com/components/autocomplete/#autocomplete) Highlights section. After trying various sol ...

I am experiencing difficulties with using the Material-UI Select component in NextJS

I am currently utilizing Material UI Select with Next.js and encountering some persistent errors on the page that I can't seem to resolve. You can view the errors in the following screenshot: https://i.sstatic.net/pIOvm.png Here is the code snippet i ...