Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda