0

I make a async function to get offers, and add to array with another array. But the offers array are looking empty in console, but when I click shows the itens.

The products are comming that's isn't the problem. The problem is that I can't add the arrayOffers to itemsArray.

OBS: the forEach is from p-interation lib.

this is my code.

useEffect(() => {
        if (auth && auth._id) {
            const fetchUserVisitedProducts = async (id) => {
                const user = await getPublicUserRequest(id);
                let array = [];

                forEach(user.offers_visited, async (id) => {
                    const offers = await getOfferRequest(id)
                    array.push(offers)
                });
                const arrayOffers = array;
                console.log(arrayOffers)
                const itemsArray = [ ...user.barbadas_visited, ...arrayOffers]
                console.log(itemsArray)
                
            }    
            fetchUserVisitedProducts(auth._id)
        }
  
    },[auth])

In the image, I see one array with 4 objects, but looks empty. And another array that is correct.

IMAGE ARRAYS

3
  • 1
    Looks like an async issue, you're not awaiting your forEach() call before logging so it's empty when first logged, but Chrome logs live arrays, so it gets updated in the view later. Commented Jan 25, 2022 at 18:21
  • 1
    Array is looking empty, but have 4 objects The reason for this is answered here: console.log of element.children shows 0 length but has three entries when expanded later Commented Jan 25, 2022 at 18:30
  • I agree with your comment ! I trying to find a soluction. Commented Jan 25, 2022 at 18:36

1 Answer 1

3

Try replacing the

 forEach(user.offers_visited, async (id) => {
    const offers = await getOfferRequest(id)
    array.push(offers)
 });

with

  for (const id of user.offers_visited) {
    const offers = await getOfferRequest(id)
    array.push(offers)
  }

as forEach is not meant to be used with async.

Sign up to request clarification or add additional context in comments.

5 Comments

This forEach is from p-interation lib, and work I another async function. PS: I try your code but didnt work :(
@JoaoVitorLima that’s an important information that belongs to the question. Anyhow, the forEach of p-interation returns a promise so await forEach(…. But if user.offers_visited is an array the for … of solution has to work.
I try to add for .. of, but shows Warning: Each child in a list should have a unique "key" prop. in console.
@JoaoVitorLima That is a react error not related to the shown code.
The for…of didnt work. Because, everthing after the function arent working.

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.