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

128
Visualizações
useState inside useEffect update datas only after re-render in react

I am trying to call a asyncronimous function inside a useEffect hook in order to avoid refetching my datas at every re-render but by doing that, my datas dosen't update before the next re-render.

My datas should load a chart, so basically my chart shows up only after re-render.

const [PricesArray, setPricesArray] = useState([]);

useEffect(() => {
      const history = Fetcher.fetchPairReservesFromBlock(3, "0xa559D24c7f9534ec19676Cd98421267EA9e02478", blockNumber, 5);
      var cast = Promise.resolve(history);
      cast.then(function(value) {
        setPricesArray(value);
      });    

    }, [])

Later, i try to use PricesArray to populate my chart like this:

const data = {
  labels,
  datasets: [
    {
      label: 'Price in $',
      data: PricesArray,
      borderColor: 'rgb(39, 146, 214)',
      backgroundColor: 'rgb(255, 255, 255, 1)',
      borderWidth: 1,
    },
  ],
};

My chart finally load but only after a re-render caused by another function. This does not happen when i fetch my datas without useEffect (but then i get re-fetching at each render).

I tried to use another useEffect that is called on PricesArray's update:

   useEffect(() => {
        setBeforePricesArray(PricesArray);
    }, [PricesArray])

I can check that this call is executed right after the first useEffect but my chart still dosen't load before the next re-render.

about 4 years ago · Juan Pablo Isaza
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