Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
Function called too fast on 'selector' component "onChange"

I need to retrieve data from my API when i change the value in my selector component. So what i did is create a function to fetch my data and i call it in my selector 'onChange'. Now my problem is that in my fetch function i use a variable that i set right before i call it. And when i change the selector value for the first time my useState variable is not set (or not detected by my app) and when i change value for the second time, it finally works. How can i resolve that ?

Selector Component :

<Select
                                                    labelId="demo-statut-label"
                                                    id="demo-statut"
                                                    defaultValue={""}
                                                    value={projetName}
                                                    onChange={handleSelectProjectChange}
                                                    input={<OutlinedInput label="Projet"/>}
                                                    MenuProps={MenuProps}
                                                >
                                                    {projets.map((projet) => (
                                                        <MenuItem
                                                            value={projet}
                                                        >
                                                            {projet.nom}
                                                        </MenuItem>
                                                    ))}
                                                </Select>

onChange function :

 const handleSelectProjectChange =  (event) => {
    setProjetName(event.target.value);
    getClientByProject();
};

Fetch Function :

function getClientByProject() {
     axios
        .get(API_URL_CLIENT_BY_ACTIVITE + projetName.id)
        .then((response) => {
            if(response.status === 200) {
                setClient(response.data);
                console.log('Response : ', response.data);

            }
        })
        .catch((error) => {
            console.log(error);
        })
}

useState :

const tab = projets !== null && projets !== undefined && projets.length > 0 ? projets[0] : {}
const [projetName, setProjetName] = useState(tab);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is a hook in react called useContext, you should try and use that, it will remove all future instances of "state hasn't updated yet". Meanwhile the quickest fix for your current troubles is this...

onChangeFunction

const handleSelectProjectChange =  (event) => {
    setProjetName(event.target.value);
    getClientByProject(e.target.value);
};

FetchFunction

function getClientByProject(project) {
     axios
        .get(API_URL_CLIENT_BY_ACTIVITE + projetName.id)
        .then((response) => {
            if(response.status === 200) {
                setClient(response.data);
                console.log('Response : ', response.data);

            }
        })
        .catch((error) => {
            console.log(error);
        })
}

Explanation: I just passed the data as an argument to the function which makes sure that the Function always has the current data.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda