using usestate variable in while loop

await watchProfit(response);



const watchProfit = async (response) => {

while (calculateProfitPercentage(response.data.avgPrice , strike) < 
incrementalBuyPercentage) {
  console.log('Checking profit...', strike);

  await new Promise((resolve) => setTimeout(resolve, 1000));
}

console.log('Profit threshold reached. Proceeding to the next iteration.');


};



const calculateProfitPercentage = (averageBuyPrice,currPrice) => {
if (averageBuyPrice === 0) {
 
  return 0;
}

console.log(averageBuyPrice,strike,'achha')
const profit = currPrice - averageBuyPrice;
const profitPercentage = (profit / averageBuyPrice) * 100;

console.log(profit,profitPercentage,)

return profitPercentage;
};

strike is useState variable

i want to pass the current strike price to watch profit for continous tracking of the profit percentage if threshold is reached it should break the while loop.

but in while loop the strike is not updating as it only taking the old strike value

how can i pass the updated strike whenever the strike is changed so that i can watch the contionous profit percentage.

  • state variables updates asynchronously, so this is expected. Provide complete context regarding how you upate state variable

    – 

Leave a Comment