1

I'm trying to fill an array with some registers from a database. However, even after retrieving said registers and place them into the array, after the loop the array stays empty

const userParties = [];

userFollowing.forEach(element => {
  // Here's when I gather the information that I need
  dispatchGetUserEvents(element.user, response => {
    userParties.push(response);
    console.log(userParties); // Here the array is full of elements, like it's supposed to be
  });
});

console.log(userParties); // However, here 'userParties' return '[]'
this.setState({ followUsersEvents: userParties });
this.setState({ userImage: userImg });

I tried to update the state array on the loop, but I had no luck there either. 'userParties' is not a state array btw.

2
  • 99% that dispatchGetUserEvents is async function so response will come later, but you try to output userParties while you didn't get result from it, so second console.log(userParties) will execute first and then will be executed console.log from response Commented May 19, 2020 at 18:44
  • Mussing definition of dispatchGetUserEvents. Commented May 19, 2020 at 18:45

1 Answer 1

1
const userParties = [];

userFollowing.forEach(element => {
  // Here's when I gather the information that I need
  dispatchGetUserEvents(element.user, response => {
    userParties.push(response);
    console.log('dispatchGetUserEvents', userParties); // Here the array is full of elements, like it's supposed to be
  });
});

console.log('outside', userParties); // However, here 'userParties' return '[]'
this.setState({ followUsersEvents: userParties });
this.setState({ userImage: userImg });

run this code and you will see that outside will be printed first and dispatchGetUserEvents later, as I mentioned in comments dispatchGetUserEvents is async function, so first will be executed console.log('outside', ...);

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

1 Comment

Thta's correct, the first thing that prints it's the 'outside', and then 'dispatchGetUserEvents'. So, how can I tackle this issue?

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.