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

255
Visualizações
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 Respostas
Responde à pergunta

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 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