reactjstypescriptmaterial-uimui-autocomplete

How to fill a MUI Autocomplete TextField with Axios response?


I made a form so you can register you pet and on the text field (pet type) theres a MUI Autocomplete component. My question is... Is it possible to, when editing this pet, the MUI Autocomplete component already contains the information from the data base? I tried this and it's not working.

//auto complete information... is working fine
const [tipos, setTipos] = useState<ITipo[]>([])

useEffect(() => {
        axios.get<ITipo[]>(`http://localhost:8080/api/v1/tipo`)
            .then(resposta => setTipos(resposta.data))

    }, [])

//this part is not working, tring to fill the TextField when editing
const [tipo, setTipo] = useState<any | null>('')

useEffect(() => {
        if (parametros.id) {
            axios.get<IAnimal>(`http://localhost:8080/api/v1/pet/${parametros.id}/`)
                .then(resposta => setTipo(resposta.data.tipo.nome))

    }, [parametros])

<Autocomplete
                onChange={(event, value) => setTipo(value)}
                disablePortal
                id="tiposAutoComplete"
                options={tiposAutoComplete}
                sx={{ width: 300, marginTop: 1 }}
                renderInput={(params) => 
                  <TextField
                    {...params}
                    value={tipo}
                    id="especieField"
                    label="Tipos"
                    variant="standard"
                    required />}
            />

Solution

  • I figured it out. The MUI Autocomplete component is a react component that contains an input, so all I had to do was to access the input inside of it, it's explained on the documentation under the topic "Controlled states".

    This is how the code looks now:

    <Autocomplete
                isOptionEqualToValue={(option, value) => option.valueOf === value.valueOf}
                value={tipo}
                onChange={(event, value) => setTipo(value as string)}
                inputValue={tipo}
                onInputChange={(event, newInputValue) => {
                    setTipo(newInputValue);
                }}
                disablePortal
                id="tiposAutoComplete"
                options={tiposAutoComplete}
                sx={{ width: 280, marginTop: 1 }}
                renderInput={(params) => <TextField
                    {...params}
                    id="especieField"
                    label="Tipos"
                    variant="standard"
                />}
            />