-1

i have a very interresting problem when using an array i get from a function that uses async:

function PriceFeed({ id, date_lte, date_gte, feeTier, liquidity, token0, token1, tickUpper, tickLower }: PriceFeedProps) {
  const { loading, error, data } = useQuery(GET_POSITION_HISTORY, {
    variables: { id: id, date_lte: date_lte, date_gte: date_gte },
  });

  //Input data
  const tokenID = Number(id)
  const initialBlock = 45159240 
  const lastBlock = 46541586

  if (loading) return <Typography>Loading...</Typography>;
  if (error) return <Typography>Error! {error.message}</Typography>;

  const [positionValueHistory, dates, hodlStratHistory] = getPositionValue(data, token0, token1, feeTier, liquidity, tickLower, tickUpper)
  const iterations = positionValueHistory.length
  console.log("number of iterations : ", iterations)

  const feesTot =  fetchFeesAtBlockNumber(tokenID, initialBlock, lastBlock, iterations)
  console.log(feesTot)
  const fees0 = feesTot[0];
  const fees1 = feesTot[1];
  console.log("fees0 are", fees0)
  console.log("fees1 are", fees1)
  


  const chart = positionValueHistory.map((principal: any, index: number) => {
  let date = new Date(dates[index] * 1000)
  console.log(index, "index")
  //console.log(fees0, fees1, "fees made")
  return {
    date: date.toLocaleDateString(),
    principal,
    fees0 : fees0,
    fees1 : fees1,
    feesUSD: 0,
    hodlStrat: hodlStratHistory[index]
  };


});

So i make a call to the fetchFeesAtBlockNumber function, which looks like this

export function fetchFeesAtBlockNumber(nftID : number, initialBlock : number, lastBlock : number, iters : number){

  //loop variables
  const iterations = Math.ceil((lastBlock - initialBlock)/iters) ;
  
  //Input data
  const tokenID = BigInt(nftID)
  const amount0 = BigInt(Number.MAX_SAFE_INTEGER) 
  const amount1 = BigInt(Number.MAX_SAFE_INTEGER)
  
  
  let Fees0dataArray : number[] = []
  let Fees1dataArray : number[] = []

  const fetchAtBlock = async () => {
    for (let currBlock = initialBlock; currBlock < lastBlock; currBlock+= iterations) {
      console.log("calling fetch at block : ", currBlock)
      try{
        const { result } = await publicClient.simulateContract({
            address: uniswapManagerAdress,
            abi: UNISWAP_MANAGER_ABI,
            functionName: 'collect',
            account: owner,
            blockNumber : BigInt(currBlock),
            args : [[tokenID, owner, amount0, amount1]]
          })
    
          Fees0dataArray.push(Number(result[0]))
          Fees1dataArray.push(Number(result[1]))
        
        }
        catch(e){
          console.log("error")
          Fees0dataArray.push(0)
          Fees1dataArray.push(0)
          continue
        }
          
    }
  }

  fetchAtBlock()
  
  const FeesArray : number[][] = [Fees0dataArray, Fees1dataArray]
  console.log("fees Array" , FeesArray)
  return FeesArray
    
  }



when calling the fetchFeesAtBlockNumber from my other component, i get an array of array of numbers as expected in the console :

fees Array [Array(0), Array(0)] => Array(0) = [0 : 0 1 : 145 2 : 221 3 : 322 4 : 507 5 : 677 6 : 3935 7 : 4359 8 : 4531 9 : 5593 10 : 6104 11 : 6595 12 : 6865 13 : 6872 14 : 6886 15 : 6913 16 : 7187 17 : 0 18 : 7313 19 : 7379 20 : 7389 21 : 7396 22 : 0 23 : 0 24 : 0 25 : 0 26 : 0 27 : 0 28 : 0 29 : 0 30 : 0 31 : 0 32 : 0 33 : 0 34 : 0 35 : 0] ,
Array(1) = [0 : 0 1 : 34668509403497 2 : 46982535571075 3 : 68908546207140 4 : 85587462972603 5 : 101817591167149 6 : 668592647980426 7 : 736959779979266 8 : 738571346571044 9 : 913762964217910 10 : 986721787059397 11 : 1013772390816656 12 : 1048481159747981 13 : 1049100792657622 14 : 1049351680200952 15 : 1094377008432846 16 : 1119292877256379 17 : 0 18 : 1171680585162875 19 : 1190338124968822 20 : 1190597553031524 21 : 1191195010166819 22 : 0 23 : 0 24 : 0 25 : 0 26 : 0 27 : 0 28 : 0 29 : 0 30 : 0 31 : 0 32 : 0 33 : 0 34 : 0 35 : 0]

I then assign each of these 2 array into their own variables in fees0 and fees1. Now here's where the problem comes : I can't access any of the variables inside each of these array since it returns "undefined" (console logs "fees1 are undefined" when console.log(fees1[index]) for any index. I don't understand why as my array is fully build, so it makes no sense that all elements inside are undefined. I really don't know where this could come from as i'm just using a basic array ?

I tried logging all values of my array, which is fully defined with 11 elements. So i can log the value of the whole array (when i log fees0 it gives me the array with all the values inside, but when i try to console.log(fees0[0] i get undefined...

Thanks in advance for your help.

HighPoint
  • 9
  • 2
  • 2
    Does this answer your question? [Is Chrome’s JavaScript console lazy about evaluating objects?](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects) – Heretic Monkey Aug 21 '23 at 17:26
  • If i understand correctly, this is only about the console. yet, here, when i try to use any value i have in the array in a chart component (from recharts), it still shows as undefined, so i don't believe the problem is due to the console... – HighPoint Aug 21 '23 at 17:37
  • 1
    "i get an array of array of numbers as expected in the console" You're getting them in the console because the browser lazily evaluates the objects. Use `console.log(JSON.stringify(fees, null, 2))` if you want to see what's in the array at the time of the log. Your question contains repeated references to `console`; I assumed you were asking about the console.j TypeScript has nothing to do with it; it's gone by the time your code is running. – Heretic Monkey Aug 21 '23 at 17:43
  • 1
    It's all due to asynchronicity; you're ordering a pizza and then complaining that you don't see the pepperoni, when you haven't even gotten the pizzas yet :) – Heretic Monkey Aug 21 '23 at 17:47
  • thanks i see now it effectively shows my array as beeing [[],[]] – HighPoint Aug 21 '23 at 17:51
  • Do you happen to know a way that would fix this ? maybe with then syntax after the call to the async function ? – HighPoint Aug 21 '23 at 17:51
  • 1
    There are several questions about that; the canonical being [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/215552) – Heretic Monkey Aug 21 '23 at 17:54

0 Answers0