javascriptreactjsapollo

TypeError: Cannot read properties of undefined (reading 'url') from API response


I am working on importing game covers from an API response based on a search and displaying them on a page.

At this point, I am able to retrieve the data for the title of the game, and the URL for the image of the cover that I need. However, I am running into an error regarding the URL of the game cover.

Error Image

TypeError: Cannot read properties of undefined (reading 'url')

This points to this line of code:

            const gameData = result.map((game) => ({
                
                gameId: game.id,
                name: game.name,
        --->    cover: game.cover.url,    <--- this line
            }));

            setSearchedGames(gameData);

My API response looks like this:

API Response

From what I can tell, the API is providing the URL and I'm unsure of why it's causing a problem. If I remove that line of code, everything runs as normal, and the results display without covers. With that line of code in, gameData returns undefined entirely. I'd be happy to add any additional code that may help.


Solution

  • This is an easy fix, when react first renders there isn't a value and obviously there's no conditions to catch this...yet

    there is syntax that will allow you to do a check with minimal coding

    example: {return data.game.url}

    fixed: {return data?.game?.url}

    just adding this simple question mark after data?. you are checking if the data has returned undefined, void or pending. You can also use this one:

    example: {data && data.game.url}