Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[material-ui][Autocomplete] Value not shown after object reaching the condition it should #41039

Closed
Hari0812 opened this issue Feb 9, 2024 · 7 comments
Assignees
Labels
component: autocomplete This is the name of the generic UI component, not the React module! package: material-ui Specific to @mui/material

Comments

@Hari0812
Copy link

Hari0812 commented Feb 9, 2024

Steps to reproduce

Link to live example: (required)
(https://stackblitz.com/edit/stackblitz-starters-pumcfo?description=React%20%20%20TypeScript%20starter%20project&file=package.json,src%2FApp.tsx&title=React%20Starter)

Current behavior

In the link i provide a code that cause unexpected behaviour the behaviour was initially i set the state to empty object and i use the values in Autocomplete tag initially it was undefined so the value is not shown after setting the value when object reaches the condition it should empty the both value of the dropdown but the selected value is shown inside the box

Expected behavior

when i set the state to empty object the text shown inside the box should become empty

Context

No response

Your environment

npx @mui/envinfo
  Don't forget to mention which browser you used.
  Output from `npx @mui/envinfo` goes here.

Search keywords: Cache

@Hari0812 Hari0812 added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Feb 9, 2024
@danilo-leal danilo-leal changed the title [material-ui][Autocomplete] [material-ui][Autocomplete] Value not shown after object reaching the condition it should Feb 9, 2024
@danilo-leal danilo-leal added package: material-ui Specific to @mui/material component: autocomplete This is the name of the generic UI component, not the React module! labels Feb 9, 2024
@EyaOuenniche
Copy link
Contributor

Hello, I found some issues in your code that could be causing the problem. In fact, There was inconsistent management of inputValue and value props for the Autocomplete components: there was an inconsistency in how you managed the inputValue prop for the second Autocomplete component. You passed an inputValue prop but did not handle it properly with an onInputChange handler. The inputValue prop in Autocomplete is used to control the text input part of the component directly, and without proper handling, it can lead to unexpected behavior.
For the first Autocomplete, you did not specify an inputValue, which is fine if you are only controlling the selected value. However, for consistent behavior, especially when resetting, you might need to manage both value and inputValue to ensure the text field and the selected item are both reset correctly.

@EyaOuenniche
Copy link
Contributor

@Hari0812
Here is a suggestion of how you can correct your code
`import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export function App() {
const [spec, setSpec] = React.useState({ first: '', second: '' });

const changeInput = (key, val) => {
const newSpec = { ...spec, [key]: val || '' };
if (Object.keys(newSpec).length === 2 && !newSpec.first && !newSpec.second) {
console.log(newSpec);
newSpec.first = ''; // Reset to empty string instead of deleting
newSpec.second = ''; // Reset to empty string instead of deleting
}
console.log(newSpec);
setSpec(newSpec);
};

return (


{spec: ${spec.first}}

{dec: ${spec.second}}



<Autocomplete
value={spec.first || ''}
onChange={(event, value) => {
changeInput('first', value);
}}
id="autocomplete-first"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="First Option" />}
/>
<Autocomplete
value={spec.second || ''}
onChange={(event, value) => {
changeInput('second', value);
}}
id="autocomplete-second"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Second Option" />}
/>

);
}
`

@Hari0812
Copy link
Author

Hari0812 commented Feb 12, 2024

Hi @EyaOuenniche
Thanks for your valuable feedback. I am still facing some issues even though I attached a value prop to two dropdowns i attached a screen recording below for your reference if you look closely the value is clear on the second/first dropdown selection but the text is still shown in the dropdown until I make another click

Screen.Recording.2024-02-12.at.7.47.45.AM.mov

FIX:
<Autocomplete
value={spec.first || ''}
onChange={(event, value) => {
changeInput('first', value);
}}
inputValue={spec.first}
id="autocomplete-first"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="First Option" />}
/>
<Autocomplete
value={spec.second || ''}
onChange={(event, value) => {
changeInput('second', value);
}}
inputValue={spec.second}
id="autocomplete-second"
options={options}
sx={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Second Option" />
)}
/>
I've set both the value and Input props to the same value. I'm unsure if this is the correct approach and I'm seeking advice on efficiency. Could you suggest an alternative method if this isn't efficient?

Thanks

@EyaOuenniche
Copy link
Contributor

Hello @Hari0812 ,
Setting both the value and inputValue props to the same state variable for your Autocomplete components might seem redundant, and it could potentially lead to the issues you're experiencing. However, I have implement your fix and it seems to be working. Here is the code that I used based on your solution.


import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export function App() {
const [spec, setSpec] = React.useState({ first: '', second: '' });

const changeInput = (key, val) => {
const newSpec = { ...spec, [key]: val || '' };
if (Object.keys(newSpec).length === 2 && !newSpec.first && !newSpec.second) {
console.log(newSpec);
newSpec.first = ''; // Reset to empty string instead of deleting
newSpec.second = ''; // Reset to empty string instead of deleting
}
console.log(newSpec);
setSpec(newSpec);
};


  return (
    <>
      <div>{`spec: ${spec.first}`}</div>
      <div>{`dec: ${spec.second}`}</div>

      <Autocomplete
value={spec.first || ''}
onChange={(event, value) => {
changeInput('first', value);
}}
inputValue={spec.first}
id="autocomplete-first"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="First Option" />}
/>
<Autocomplete
value={spec.second || ''}
onChange={(event, value) => {
changeInput('second', value);
}}
inputValue={spec.second}
id="autocomplete-second"
options={options}
sx={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Second Option" />
)}
/>
    </>
  );
}

@Hari0812
Copy link
Author

Hi @EyaOuenniche
May I know what changes you made to remove the redundant value for inputValue and Value prop I don't see any difference in it?
Thanks : )

@EyaOuenniche
Copy link
Contributor

Actually there I did not, I just reproduced your code and added this part

const [spec, setSpec] = React.useState({ first: '', second: '' });

const changeInput = (key, val) => {
const newSpec = { ...spec, [key]: val || '' };
if (Object.keys(newSpec).length === 2 && !newSpec.first && !newSpec.second) {
console.log(newSpec);
newSpec.first = ''; // Reset to empty string instead of deleting
newSpec.second = ''; // Reset to empty string instead of deleting
}
console.log(newSpec);
setSpec(newSpec);
};

If you would like to remove the redundant value for inputValue and value prop, you need to separate them into 2 different states. here is my suggestion:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export function App() {
  const [spec, setSpec] = React.useState({ first: '', second: '' });
  const [inputValues, setInputValues] = React.useState({ first: '', second: '' });

  const changeInput = (key, val) => {
    const newSpec = { ...spec, [key]: val || '' };
    if (Object.keys(newSpec).length === 2 && !newSpec.first && !newSpec.second) {
      console.log(newSpec);
      // Intended reset logic
      newSpec.first = ''; // Reset to empty string instead of deleting
      newSpec.second = ''; // Reset to empty string instead of deleting
    }
    setSpec(newSpec);
  };

  const handleInputChange = (key, value) => {
    setInputValues((prevValues) => ({ ...prevValues, [key]: value }));
  };

  return (
    <>
      <div>{`spec: ${spec.first}`}</div>
      <div>{`dec: ${spec.second}`}</div>

      <Autocomplete
        value={spec.first || ''}
        onChange={(event, value) => changeInput('first', value)}
        inputValue={inputValues.first}
        onInputChange={(event, value) => handleInputChange('first', value)}
        id="autocomplete-first"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="First Option" />}
      />
      <Autocomplete
        value={spec.second || ''}
        onChange={(event, value) => changeInput('second', value)}
        inputValue={inputValues.second}
        onInputChange={(event, value) => handleInputChange('second', value)}
        id="autocomplete-second"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Second Option" />}
      />
    </>
  );
}

@Hari0812
Copy link
Author

Thanks :)
I close this issue

@github-actions github-actions bot removed the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Feb 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: autocomplete This is the name of the generic UI component, not the React module! package: material-ui Specific to @mui/material
Projects
None yet
Development

No branches or pull requests

4 participants