React Component Not Showing Dropdown Suggestions from Dynamic State

40 views Asked by At

I'm developing a React component named CadastroPacienteBiopsia for registering patients and biopsies. The component has a feature where it dynamically searches for professionals as the user types in a text input field. While the search functionality works (the state updates with fetched data and logs correctly), the dropdown suggestions are not being displayed.

Here's the relevant part of my component:

import React, { useState, useEffect } from 'react'
import axios from 'axios';
import './formulario_design.css'

function CadastroPacienteBiopsia({ onFormSubmit }) {
    // ... (state and other functions)

    const [profissionais, setProfissionais] = useState([]);
    const [textoBusca, setTextoBusca] = useState('');

    useEffect(() => {
        const buscarProfissionais = async () => {
            if (textoBusca.length > 2) {
                try {
                    const resposta = await axios.get(`http://localhost:5000/api/profissionais/nome/${textoBusca}`);
                    setProfissionais(resposta.data);
                } catch (erro) {
                    console.error('Erro ao buscar profissionais', erro);
                }
            }
        };

        const timerId = setTimeout(buscarProfissionais, 500); // Debounce
        return () => clearTimeout(timerId);
    }, [textoBusca]);

    // ... (other parts of the component)

    return (
        <div className="formulario-cadastro">
            {/* Other form fields */}
            <input
                type="text"
                name="profissional_nome"
                placeholder="Digite o nome de um profissional existente"
                value={dadosPaciente.profissional_nome}
                onChange={(e) => {
                    handleInputChange(e);
                    setTextoBusca(e.target.value);
                }}
                list="profissionais-list"
            />
            <datalist id="profissionais-list">
                {profissionais.map((profissional, index) => (
                    <option key={index} value={profissional.nome} />
                ))}
            </datalist>
            {/* Other form fields */}
        </div>
    );
}

export default CadastroPacienteBiopsia;

The state profissionais updates as expected when typing in the profissional_nome field, and the console log confirms the fetched data. However, the dropdown list tied to this input field (datalist with id "profissionais-list") does not display the suggestions based on the fetched data.

How can I make the dropdown suggestions appear as the user types in the "Digite o nome de um profissional existente" field?

In an attempt to resolve an issue with my React component CadastroPacienteBiopsia, I've implemented a feature to dynamically display professional suggestions in a dropdown list as the user types in a text field. Despite successful data fetching and state updates confirmed through console logs, the dropdown list, linked via a datalist tag, is not displaying these suggestions. I've employed useState for managing state and useEffect for triggering professional searches, with an added debounce for efficiency. The core challenge remains: the dropdown is not reflecting the dynamically loaded data.

1

There are 1 answers

2
DeveloperLV On

Is datalist a custom component that you have made?

If yes

Please share the code

If no

Try list the items using ul and li elements like so:

 {profissionais.length > 0 && (
    <ul className="suggestions-list">
      {profissionais.map((profissional, index) => (
        <li key={index}>
          {profissional.nome}
        </li>
      ))}
    </ul>
  )}