Skip to content

Commit

Permalink
add a warning to useAutocomplete when the value doesn't exist in options
Browse files Browse the repository at this point in the history
  • Loading branch information
igorbrasileiro committed Mar 22, 2020
1 parent 27471b4 commit 11bc268
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -775,12 +775,18 @@ describe('<Autocomplete />', () => {
});

describe('warnings', () => {
let consoleWarnContainer = null;

beforeEach(() => {
consoleErrorMock.spy();
consoleWarnContainer = console.warn;
console.warn = spy();
});

afterEach(() => {
consoleErrorMock.reset();
console.warn = consoleWarnContainer;
consoleWarnContainer = null;
});

it('warn if getOptionLabel do not return a string', () => {
Expand Down Expand Up @@ -836,6 +842,25 @@ describe('<Autocomplete />', () => {
'The component expects a single value to match a given option but found 2 matches.',
);
});

it('warn if value does not exist in options list', () => {
const value = 'not a good value';
const options = ['first option', 'second option'];

render(
<Autocomplete
{...defaultProps}
value={value}
options={options}
renderInput={(params) => <TextField {...params} />}
/>,
);

expect(console.warn.callCount).to.equal(4);
expect(console.warn.args[0][0]).to.include(
'Material-UI: you have provided an out-of-range value `"not a good value"` for the autocomplete component.',
);
});
});

describe('prop: options', () => {
Expand Down
25 changes: 25 additions & 0 deletions packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,31 @@ export default function useAutocomplete(props) {

popupOpen = freeSolo && filteredOptions.length === 0 ? false : popupOpen;

if (process.env.NODE_ENV !== 'production') {
if (value !== null && !freeSolo && options.length > 0) {
const missingValue = (multiple ? value : [value]).filter(
(value2) => !options.some((option) => getOptionSelected(option, value2)),
);

if (missingValue.length > 0) {
console.warn(
[
`Material-UI: you have provided an out-of-range value${
missingValue.length > 1 ? 's' : ''
} \`${
missingValue.length > 1
? JSON.stringify(missingValue)
: JSON.stringify(missingValue[0])
}\` for the autocomplete ${id ? `(id="${id}") ` : ''}component.`,
'',
'Consider providing a value that matches one of the available options.',
'You can use the `getOptionSelected` prop to customize the equality test.',
].join('\n'),
);
}
}
}

const focusTag = useEventCallback((tagToFocus) => {
if (tagToFocus === -1) {
inputRef.current.focus();
Expand Down

0 comments on commit 11bc268

Please sign in to comment.