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

234
Visualizações
Why is my OnChange function not logging the first value I click on but only starts logging after the second click?

I'm working on a component in my react app that allows for users to select multiple foods in a drop down list. I'm experiencing a problem where the first food item I select is logged as an empty array so every food item I select after that is delayed by one food item. For example, let's say the first food item I select from the dropdown is "Fries", then console.log(foods) will log an empty array. If the second item I select is "Burgers", then the console will log [Fries]. If the third item I select is "Salad", then the console will log [Fries, Burgers]. I'm pretty stuck so any help would be appreciated!

This is where the handle change function is called on the dropdown menu:

<Select
    className={classes.dropDownMenu}
    options={listItems}
    onChange={value => handleChange(value)}
/>

This is my function for handling change on dropdown:

const [foods, setFoods] = React.useState([])

const handleChange = value => {
  setFoods(prev => [...prev, value])
  console.log(foods)
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Have you tried to pass the set state of foods like this...

   const handleChange = value => {
      setFoods(() => [...foods, value])
      console.log(foods)
   }

that should use the original data and add new data to the state by spreading the original state into the array and adding the value passed in from your Select component.

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