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

121
Visualizações
Both states are getting updated only after the second event call in React

I have 2 functions. One is getting called when I type on the search input. The second one is getting called when I select a category. Default value for search is '' and for selectedCategories null. However when I type first time or click category first time. First time the functions are getting called with the default values of both states. It looks like I am always 1 step before the right one.

const onTextChanged = (e: ChangeEvent<HTMLInputElement>) => {
            const value = e.target.value;
            setIsComponentVisible(true);
            setSearch(value);
        };
    
        const selectCategory = async (category) => {
            const { id } = category;
            if (!selectedCategories || !selectedCategories[id]) {
                setCategories((prevState: any) => ({
                    ...prevState,
                    [id]: category
                }));
            } else {
                setSelectedCategories((prevState: any) => {
                    const { [id]: undefined, ...rest } = prevState;
    
                    return rest;
                });
            }
        };

What is wrong and how it can be fixed?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you are trying to console.log() your states, right after your state setter is called, your state probably would not be updated by then because React sets the state asynchronously. useEffect can help you with that, you can console.log() your state every time it changes. Something like this:

useEffect(() => {
  console.log(search)
}, [search])
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