Home > database >  Destructure array to display API results
Destructure array to display API results

Time:03-18

I'm trying to display results from an API but it seems like an entire section of the page isn't being returned. There are no errors present so solving this has been somewhat confusing.

My assumption is that based on the way the API has returned the data, my current setup for destructuring the data is incorrect. Here is the response I receive in the console from the API.

API Results

I want to apend these results to a page to display the name and cover of these video game titles.

Section displaying results

            <Container>
                <h2>
                    {searchedGames?.length
                        ? `Viewing ${searchedGames.length} results:`
                        : 'Search for a game to begin'}
                </h2>
                <CardColumns>
                    {(searchedGames || []).map((game) => {
                        return (
                            <Card key={game.gameId} border='dark'>
                                {game.cover ? (
                                    <Card.Img src={game.cover} alt={`The cover for ${game.name}`} variant='top' />
                                ) : null}
                                <Card.Body>
                                    <Card.Title>{game.name}</Card.Title>
                                </Card.Body>
                            </Card>
                        );
                    })}
                </CardColumns>
            </Container>

Form Handler

    const handleFormSubmit = async (event) => {
        event.preventDefault();

        if (!searchInput) {
            return false;
        }

        try {
            

            const response = await getGame(searchInput);

            if (!response.ok) {
                throw new Error('Something went wrong...');
            }

            const { result } = await response.json();

            const gameData = result?.map((game) => ({
                
                gameId: game.id,
                name: game.name,
                cover: game.cover.url,

            }));

            setSearchedGames(gameData);
            setSearchInput('');
        } catch (err) {
            console.error(err);
        }
    };

Upon searching, I receive the API response with the appropriate data, but the page does not display anything at all (not even the "Viewing xxx number of results" section, which I feel is a clue pointing to the searchedGames array.) I'd be happy to add any extra information or code if someone would like. I feel like there is a simple solution but I have been unable to find the method to fix this. Thank you in advance for any assistance anyone can offer!

EDIT:

There was a helpful response here recommending I check my searchedGames array and, once I did, I saw that it was empty. So the data from the API is not getting put into the "searchedGames" array. I am researching how to fix this, but if anyone responds to the question I feel this may be a helpful detail to assist. The problem is that my searchedGames array is not being filled with the API data.

EDIT 2:

export const getGame = (searchInput) => {
    return fetch(`***********`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        const accessToken = data.access_token;


        return fetch(`https://fathomless-river-46653.herokuapp.com/https://api.igdb.com/v4/games/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Client-ID': '********',
                'Authorization': `Bearer ${accessToken}`
            },
            body: `
                search "${searchInput}";
                fields name,cover.url;`
        })
        
    });
};

CodePudding user response:

Not entirely sure if there are details missing on the actual API response data format but I'll try giving an answer.

The json() method of fetch returns the response body of your HTTP request as JSON. So with your response data being the one of your first screenshot, it's an array of objects but not an object with an result attribute. However, latter is what you assume in your code:

const { result } = await response.json();

Then you proceed as if result was the response array of your first screenshot while it actually is undefined, so that gameData resolves to undefined after optional chaining.

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

Try out using the JSON response directly without destructuring. This should give you the actual array of game objects:

const result = await response.json();
  • Related