0

I have never experienced an error like this before, my brain cannot compute how it makes sense:

 const getProfileImages = async () => {
    for (let i = 0; i <= recommendedUsers.length; i++) {
        console.log(recommendedUsers[0].userId)
        const response = await UserService.downloadProfileImage(recommendedUsers[i].userId)
            .then(res => res.blob())
            .then(blob => {
                const imgBlob = blob;
                const reader = new FileReader();
                reader.readAsDataURL(imgBlob);
                reader.onloadend = () => {
                    const base64data = reader.result;
                    images[i] = base64data;
                };
            });
    }
}

This method as is returns 'Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'userId') at getProfileImages (SwipeCard.js:50:1)'

However, when I comment out the const response section:

const getProfileImages = async () => {
    for (let i = 0; i <= recommendedUsers.length; i++) {
        console.log(recommendedUsers[0].userId)
        /*
        const response = await UserService.downloadProfileImage(recommendedUsers[i].userId)
            .then(res => res.blob())
            .then(blob => {
                const imgBlob = blob;
                const reader = new FileReader();
                reader.readAsDataURL(imgBlob);
                reader.onloadend = () => {
                    const base64data = reader.result;
                    images[i] = base64data;
                };
            });
    }
    
         */
}

}

The page renders fine (obviously without images) and the console.log(recommendedUsers[0].userId) statement prints out the user id's correctly. If I try to console.log(recommendedUsers[i].userId) it suddenly has a meltdown again.

Are recommendedUsers[0] and recommendedUsers[i] where i = 0 not equivalent?

devo9191
  • 219
  • 3
  • 13
  • 2
    `Are recommendedUsers[0] and recommendedUsers[i] where i = 0 not equivalent?` Are you sure `i` is still 0 when the error occurs? I would expect the error to occur at the end of the loop, because your condition is `i <= recommendedUsers.length;`, not `i < recommendedUsers.length;` – Nicholas Tower Aug 17 '22 at 20:28
  • Is recommendedUsers also retrieved from an ajax call? – James Aug 17 '22 at 20:29
  • It's probably because of `<=` as @NicholasTower stated – Konrad Aug 17 '22 at 20:30
  • 1
    `i <= recommendedUsers.length` -> `i < recommendedUsers.length` because when `i = recommendedUsers.length` then it's out of bounds. – VLAZ Aug 17 '22 at 20:30

0 Answers0