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

256
Vistas
Can we change state before making an API call which uses that state? React
 useEffect(() => {
    resetState();
    if (page === 'ADMISSION') {
      fetchAdmissionKitPosts();
    } else if (page === 'WEEKLY') {
      fetchWeeklyKitPosts();
    } else if (page === 'FESTIVAL') {
      fetchFestivalKitPosts();
    }
  }, [page]);

So I want to make different API calls based on the page variable. I have to reset the state before making those calls. But while making the call I'm getting the previous state. I came to know that the setState in react is async in nature, so I assume that that's why I'm getting the previous state in the API call functions.

So my question is, how can I make it so that these API calls only run after the state has been reset?

I know that I can use a callback function in the class-based component with the setState function. But I want to keep this component functional.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can implement setState callback in functional component with useEffect. if i'm getting it right, you are using two state variables page and posts, if this is the case you should use two useEffect methods like this:

useEffect(() => {
   if(page !== ''){
    setMarketingPosts([])
   } 
  }, [page]);

  useEffect(() => {
    if (page === 'ADMISSION') {
      fetchAdmissionKitPosts();
    } else if (page === 'WEEKLY') {
      fetchWeeklyKitPosts();
    } else if (page === 'FESTIVAL') {
      fetchFestivalKitPosts();
    }
    setNextPageToken('')
  }, [post]);
about 4 years ago · Santiago Trujillo 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