0

I have a Functional Component that retrieves a list of objects upon rendering. Then, I run a foreach loop with it and it works perfectly! Afterwards, I make http requests with each of these objects to make a new array of objects... But I can't use its foreach, as if I formatted something wrong. I printed both arrays to the console and they look different. Help Please!!

interface minterface
{result: string;
  res: number;
  pos: number;
}
let analyzedAppReviews: minterface[] = [];
    try {
  const { data } = await ailab.post(
    `text/classification/predict/${ailabKey}`,
    {
      text: reviewText,
    }
  );
  let aiLabObj = {} as ailabInterface
  aiLabObj.result = data.result;
  aiLabObj.confidence_score = data.confidence_score;
  aiLabObj.processing_time = data.processing_time;
  analyzedAppReviews.push(aiLabObj);
}

2 array instances array with values

3
  • I suspect that you are trying to use analyzedAppReviews before the promises have resolved. You would need to use Promise.all() to resolve them all or you could make analyzedAppReviews be a state and make a setState call to set each element when it is resolved. Commented Apr 15, 2021 at 0:41
  • I am printing the object that is being received inside the function. I can't create a statevariable for this one because I need to do independent http requests. It'd re-render a lot of times and ends crashing Commented Apr 15, 2021 at 1:08
  • Im adding another picture of the array with values Commented Apr 15, 2021 at 2:10

1 Answer 1

1

As Linda suggested. I changed the foreach loop for a Promise.all since I had to make multiple http requests. Worked like a charm, thank you very much. This is the proper way to do it with axios :) Also, after a bit of searching, it's a big NO to use foreach loops to make http requests. To anybody thinking of using it for that. Promise.all guys!

    let requestsArray = reviews.map((review: { body: string }) => {
  const request = ailab.post(`text/classification/predict/${ailabKey}`, {
    text: review.body,
  });

  return request;
});
Promise.all(requestsArray).then((values) => {
  let tmpList = values.map((value: any) => {
    return value.data;
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.