0

I have been trying to fetch this data from https://bad-api-assignment.reaktor.com/rps/history to my node.js back-end and display it on my React front-end.

I can somehow make it work and see the data at the console, but when refreshing the front-end page, I will get errors like this when trying to handle the data again:

Console error messages after page refresh

App.js:

import axios from "axios";
import React from "react";
import GameData from "./GameData";

export default function App() {
  const [games, getGames] = React.useState(null);
  const baseURL = "http://localhost:5000";

    React.useEffect(() => {
       getAllGames();
    }, []);

    const getAllGames = async () => {
        await axios.get(baseURL)
        .then((response) => {
            const allGames = response.data.data;
            //console.log(allGames)
            getGames(allGames);
        })
        .catch(error => console.error('Error: $(error'));
    }
        return(
            <GameData games={games}/>
        )
}

GameData.js:

import React from 'react';

export default function GameData(props) {
    const displayGames = (props) => {
        const {games} = props;

        console.log(games)

        games.map((game, index) => {
            console.log(game, index);
                return(
                    <div className='game' key={game.type}>
                    </div>
                )
        }
        )
    }
    return(
        <>
        {displayGames(props)}
        </>
    )
}

On GameData.js, if I comment this section:

//games.map((game, index) => {
//  console.log(game, index);
//      return(
//          <div className='game' key={game.type}>
//          </div>
//      )
//}
//)

I can see that console.log(games) at my console. Then I can un-comment those lines and save on React, and it will display mapped data on console:

Console after un-commenting code and saving on React.

Okay so perfect, it works so far as I wish, but if I refresh the page on my browser, I will face the error/null issue

Console error messages after page refresh.

I have been trying to Google that but could not figure it out. How to solve issue like this? I should be able to sort that data later as well and so on.

Hope it makes sense.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
koodikari
  • 9
  • 1
  • 2
    This is an extremely common beginner's error which is simply caused by `const [games, getGames] = React.useState(null);` instead of the correct `const [games, getGames] = React.useState([]);` I would also advise to use the proper naming convention of `setGames`, because it's a setter method, not a getter. –  Jan 07 '22 at 12:26
  • 1
    data is async so you should add check conditions ```games && games.map()=>``` , props is getting undefined because the page gets rendered then the apis's data is getting hit and then it is getting stored in ```games``` alos change the setstate to just an empty array ```useState([])``` – Shoyeb Memon Jan 07 '22 at 12:27
  • The cause of the error is `games.map` being hit while `games` is `null`. –  Jan 07 '22 at 12:27
  • 1
    Duplicate: [Error : Cannot read property 'map' of undefined](https://stackoverflow.com/questions/24706267/error-cannot-read-property-map-of-undefined) –  Jan 07 '22 at 12:28
  • Thank you for the all comments, and for the edit where I failed to fetch the image correctly! @ChrisG Thank you! Changing the null to array solved my issue, and I agree with the getGames-->setGames! – koodikari Jan 07 '22 at 12:42

1 Answers1

0

first check if array is not empty then loop through it:

//GameData.js
export default function GameData({ games }) {
return(
    <>
    {games.length > 0 && games.map((item) => (
        <div key={item.id}>
               {item.name}
         </div>
      ))
    </>
)

}

Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15