Cuando el primer autocomplete se asigna un valor, hace una llamada a una API para popular el segundo Autocomplete.
El problema es que si selecciono un valor del primero, selecciono uno del segundo (ya populado) e intento cambiar el primero de nuevo, el valor elegido en el segundo se queda pegado, aunque si cambien las opciones, el segundo autocomplete no se limpia, entonces tengo seleccionada una opción que no pertenece a la cadena de dependencias de los dropdown. ¿Cómo puedo hacer para vaciar el segundo autocomplete antes que se haya la llamada? Intenté esto
value={subSections[0]}
Pero me arroja este error:
useControlled.js:18 MUI: A component is changing the uncontrolled value state of Autocomplete to be controlled. Elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled Autocomplete element for the lifetime of the component. The nature of the state is determined during the first render. It's considered controlled if the value is not
undefined
.
Este es mi componente
import { Header } from './shared/components'
import {
Box,
Container,
Grid,
Autocomplete,
TextField,
FormControl,
Paper
} from '@mui/material'
import './App.scss';
import { useEffect, useState } from 'react';
const sectionOptions = [
{ id: 'menu', label: 'Menú'},
{ id: 'content', label: 'Contenido'},
{ id: 'questions', label: 'Preguntas frecuentes'}
];
export const App = () => {
// prepare the states for data
const [ sections, setSections ] = useState(sectionOptions);
const [ subSections, setSubsections ] = useState([]);
const [ rawSubSections, setRawSubsections ] = useState([]);
const [ selectedSubsection, setSelectedSubsection ] = useState({});
// on first dropdown changed
const sectionChanged = async ( evt, value ) => {
setSubsections([]);
setRawSubsections([]);
if ( value && value.id ) {
const result = await callApi( value.id );
if( result ) {
const data = result.map( ({id, label}) => ({ id, label }) )
setSubsections( data );
setRawSubsections( result );
}
}
}
// On second subsection has been changed
const subSectionChanged = async ( evt, value ) => {
if( value && value.id ) {
const subSection = rawSubSections.find( sub => sub.id === value.id );
console.log( subSection );
}
}
// general API Call
const callApi = async ( endpoint ) => {
if( !endpoint ) return;
const url = `http://localhost:3000/${endpoint}`;
try {
const response = await fetch( url );
const result = await response.json();
return result;
} catch ( error ) {
console.log( error );
return;
}
}
return (
<>
<Header />
<Box sx={{
flexGrow: 1,
marginTop: '2rem',
}}>
<Container>
<Grid container spacing={3}>
<Grid sm={4} xs={12}>
<FormControl fullWidth size='small' >
<Paper elevation={8}>
<Autocomplete
options={sections}
renderInput={(params) => <TextField {...params} label="Secciones" />}
onChange={sectionChanged}
name="sections"
></Autocomplete>
</Paper>
</FormControl>
</Grid>
<Grid sm={4} xs={12}>
<FormControl fullWidth size='small' >
<Paper elevation={8}>
<Autocomplete
value={subSections[0]}
options={subSections}
renderInput={(params) => <TextField {...params} label="Subsecciones" />}
name="subSections"
onChange={subSectionChanged}
></Autocomplete>
</Paper>
</FormControl>
</Grid>
</Grid>
</Container>
</Box>
</>
)
}