Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

39
Vistas
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.

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.