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

151
Visualizações
useState has previous value instead of the current

I'm new to react and I'm trying to understand how it's working.

I have 2 select inputs and on change event I want to filter the other's select values based on the first one.

After calling setOptions with the filtered values, they are always one step behind - so I have the previous value each time.

I understand that useState is async and I tried with and useEffect (() => {}, [options]) and I still have the previous values in options.

 const [options, setOptions] = useState<any>()
 const filterOptions = (ids: string[]) => {
        const filteredOptions = list.filter(item=> {
            return list.includes(item.id)
        })
        setOptions(filteredOptions)
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think your primary problem is from the logic itself. list.includes(item.id) is checking item.id on list that always returns true.

You can modify it to ids.includes(item.id)

 const [options, setOptions] = useState<any>()
 const filterOptions = (ids: string[]) => {
        const filteredOptions = list.filter(item => {
            return ids.includes(item.id)
        })
        setOptions(filteredOptions)
    }

Shorter version

 const [options, setOptions] = useState<any>()
 const filterOptions = (ids: string[]) => {
        const filteredOptions = list.filter(item => ids.includes(item.id))
        setOptions(filteredOptions)
    }
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