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.