The autocomplete feature fails to display any suggestions and doesn't allow me to input a new value

I am currently working with Material UI Autocomplete and react-hook-form to create a modal, but I am facing an issue where I cannot display a value and change it simultaneously. If I pass the default value to InputValue, it appears on the screen but cannot be edited via input. However, if I place it in value, it does allow me to change values through input and select, but the value itself doesn't show up on the screen.

This is the component being rendered:

<Autocomplete
      id={name}
      options={options}
      getOptionLabel={(option) => (option.descricao ? option.descricao : "")}
      filterOptions={filterOptions}
      onChange={(e, options) =>
        // console.log(options)
        setValue(name, options?.descricao)
      }
      // onInputChange={(e, v) => setValue(name, v)}
      value={cnae ? cnae : ""}
      inputValue={cnae ? cnae : ""}
      renderOption={(props, options) => (
        <Box component="li" {...props}>
          {options.id +
            "/" +
            options.grupo.divisao.id +
            ", " +
            options.descricao}
        </Box>
      )}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          {...other}
          label={label}
          error={Boolean(errors[name])}
          helperText={errors[name] ? errors[name].message : ""}
        />
      )}
    />

These are the props being passed:

<ACCnae
                    name="cnae"
                    label="Ramo"
                    fullWidth
                    errors={errors}
                    options={context.cnae}
                    setValue={setValue}
                    cnae={getValues("cnae")}
                    required
                  />

Despite typing here, only clearing and selecting seem to work. https://i.stack.imgur.com/DfvtV.gif

Answer №1

After some trial and error, I have managed to make it functional. However, I must admit that my approach may not be the most efficient or optimal method to achieve the desired outcome. Initially, I identify the entire object required for setting the autocomplete value, as this is crucial for successful implementation. If the object is already defined, I utilize the setValue function from react-hook-form to update the data object with the new value.

React.useEffect(() => {
    if (!obj) {
      setObj(options.find((item) => item.descricao === cnae));
    }
    if (obj?.descricao) {
      setValue(name, obj.descricao);
    }
  }, [cnae, obj]);

The main modification I made in the previous component is altering the onChange function to accept setObj as a parameter

<Autocomplete
      id={name}
      options={options}
      getOptionLabel={(option) => option?.descricao}
      filterOptions={filterOptions}
      onChange={(e, options) => setObj(options)}
      value={obj ? obj : ""}
      renderOption={(props, options) => (
        <Box component="li" {...props}>
          {options.id +
            "/" +
            options.grupo.divisao.id +
            ", " +
            options.descricao}
        </Box>
      )}
      loading={loading}
      renderInput={(params) => (
        <TextField
          {...params}
          {...other}
          label={label}
          error={Boolean(errors[name])}
          helperText={errors[name] ? errors[name].message : ""}
        />
      )}
    />

If you have any suggestions on improving this process or know of a more straightforward solution, please feel free to share your insights

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

Although the state's value remains the same, a React functional component may still re-render once

Recently, I have become a fan of the React Functional Component and have been experimenting with it. However, I encountered an unusual case that left me puzzled. In my project, I created a custom-hook named "useAutoIncrement" which utilizes a setInterval ...

Error: Jest react testing encountered an issue when attempting to read the property 'type' from an undefined value

While conducting tests on my app components created with the material UI library using jest and enzyme, I encountered an error in one of my packages. Here is a screenshot of the error: Click here to view ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

Understanding the Issue: Why Doesn't Signing Up with an Existing Account Automatically Log In When Using the 'autoconfirm' Feature in Supabase Authentication?

When using the supabase.auth.signUp function in my code, I expected a logged-in session with "autoconfirm" enabled on the server. However, after signing up with an existing account, it didn't log me in as anticipated. Here's a snippet of the code ...

Vite build error: TypeError - Unable to access properties of null while trying to read 'useContext'

I used the following component imported from material-ui : import Paper from '@mui/material/Paper'; After running npm run build followed by npm run preview, I encountered an error in the console: Uncaught TypeError: Cannot read properties of n ...

Developing the search feature using Sequelize

Before diving into the question, let's take a look at the structure of the post table in my current project. module.exports = class Post extends Model { static init(sequelize) { return super.init({ title: { type: DataTypes.TE ...

Tips for maintaining data in a React component across re-renders?

Currently, I am working on creating a basic axios call to communicate with a nodejs server from a react application in order to retrieve products stored in a mongoose schema model. The issue I am facing is that when the page initially loads, I can successf ...

Having trouble displaying the collection data from firebase using React

I am having an issue retrieving a collection from firebase and then using a map function to loop through the documents and render some UI elements. The data is correctly logged in the console at line 20, however, the map function doesn't seem to be wo ...

Tips for successfully passing an empty value as a prop on a Material UI button

Currently, I am utilizing a ternary operator in a prop for a button. It is functioning as expected, but a warning regarding the empty string keeps appearing in the browser. I am looking for an alternative solution to avoid this error. <Button varia ...

Customize Material-UI icons dynamically by changing their props in an array

I am looking to change props (color, size) for multiple icons in an array using Material-UI v4: const ICONS_ARRAY: React.ReactNode[] = [ <AlertCircleCheckOutline />, <AppleSafari />, <MotionPlay />, <AppleKeyboardCommand />, <Fil ...

React Material UI and DayJs are not syncing up properly when displaying dates

In my React application, I am using MUI Cards to display a list of objects. One of the fields in these objects is of type date in postgres. When I retrieve a sample card object from the database, this is the value that appears in the browser console: { ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Every time I attempt to execute an npm command, I encounter the error message "spawn bash ENOENT."

I'm encountering an error Attempting to execute any npm command results in the spawn bash ENOENT error, preventing me from moving forward. Can someone offer assistance please? ...

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

Clicking the button becomes impossible after entering text and using `evaluateJavascript`

I am currently working on finding a solution to input the receipt number and click the 'Check Status' button on this specific website: After successfully entering the receipt number: document.getElementById('receipt_number').value = &a ...

When a parameter is passed into a React-Query function with an undefined value, it can lead to the API returning a 404 error

Two parameters are sent from the frontend to trigger a GET request in another TypeScript file. It seems that one of the parameters is not successfully passed due to unknown rerenders, resulting in a 404 Error being returned by the API call in the console. ...

Prevent regex from matching leading and trailing white spaces when validating email addresses with JavaScript

In my current setup, I utilize the following regular expression for email validation: /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ My attempt to validate the email is shown below: if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\. ...

Toggle the Material UI checkbox based on the value received from an object input

I am facing an issue with an unchecked checkbox in my project. I am attempting to update its value based on data retrieved from an object. The object contains boolean values from an SQL query, either 'T' for true or 'F' for false. My in ...

Using Node.js Express to serve a React build version

When I try to serve my react application with an Express server, I run into a problem. I have set up the react application to make API requests via a proxy, but now that I am serving the build using Node.js, all API routes are returning a 404 error. &quo ...