make an array.push inside a map is getting overwriting previous data (reactJs)

I have an Array (A) that return me many items used in the params function of my Api Call, so I made a map with this array, and for each item, I make an API Call and with a .then, with the data response want create a new array (B).

the problem: the array B is made with the same amount of items, but these items are getting repeated, instead of a unique item.

my code:

useEffect(() => {
  // the Array A in the question / // 

    moviesId.arr.map((item) => {

  // the Api Call function in the question /  //    
 
      ApiMovieList(item).then((data) => {

        let a = [];

        for (var x = 0; x < moviesId.arr.length; x++) {
          a.push(data.poster_path);
        }

     // the Array B in the question / //  

         var UserDataEntry = a || [];

        
         console.log(UserDataEntry);
 


      });
    });
  });

Console show this:

    (2) ["Matrix", "Matrix"] 
      
       Instead of this:
   (2) ["Ghost", "Matrix"]

How do I solve that, please?

my data:

moviesId.arr = ["451048", "436969"]

ApiMovieList(item).then((data) => data is equal a string (“Matrix”, “Ghost”, for example, it depends of the position of the moviesId.arr

Answer

You should not use .map for side-effects. You are iterating moviesId.arr array and then for each element pushing moviesId.arr.length number of data.poster_path values into array a. This is where your duplicates are coming from.

I suggest loading up the ApiMovieList(item) calls in an array of Promises and use Promise.all to wait for all of them to resolve. You’ll then have a resolved array of poster paths to set to UserDataEntry and log.

useEffect(() => {
  // the Array A in the question
  const posterReqs = moviesId.arr.map(item => {
    return ApiMovieList(item).then(data => data.poster_path);
  });

  Promise.all(posterReqs).then(posters => {
    // the Array B in the question
    const UserDataEntry = posters || []; 
    console.log(UserDataEntry);
  });
});