1

I am doing a bit of practice and built a few apis to interact with via my front end. I have now refactored my code to use hooks. However, I am getting the error "games.map" is not a function with my map method.

ERROR BELOW

TypeError: games.map is not a function
Games
src/components/pages/games/Games.js:29
  26 |     </div>
  27 |   </div>
  28 | </div>
> 29 | <div className="text-white text-dark">
     | ^  30 |   {games.map(game => {
  31 |     return <GameCard games={game} key={game.name} />;
  32 |   })}
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
src/components/pages/games/Games.js:14
  11 | 
  12 | const fetchAllGames = () => {
  13 |   api.getAllGames().then(games => {
> 14 |     gameState({ games });
     | ^  15 |   });
  16 | };
  17 | 
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

See below component in which I am trying to map through, any help with the map refactoring would be great :)

import * as api from '../../../api';
import GameCard from '../gameCards/GameCards';

const Games = () => {
  const [games, gameState] = useState([]);

  useEffect(() => {
    fetchAllGames();
  });

  const fetchAllGames = () => {
    api.getAllGames().then(games => {
      gameState({ games });
    });
  };

  return (
    <div>
      <div className="container-fluid" style={{ height: 35 }}>
        <div className="row">
          <div className="col">
            <button to="" className="btn btn-primary">
              Add New Game
            </button>
          </div>
        </div>
      </div>
      <div className="text-white text-dark">
        {games.map(game => {
          return <GameCard games={game} key={game.name} />;
        })}
      </div>
    </div>
  );
};

export default Games;

2 Answers 2

1

Solution :

Since useState has Array as initialState You should use gameState(games) instead of gameState{games}

const fetchAllGames = () => {
    api.getAllGames().then(games => {
      gameState( games );
    });
  };

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

Comments

1

.map only works in arrays, not objects

   api.getAllGames().then(games => {
      gameState({ games });
    });

in here you are setting state game with an object.

I have no idea what games contain, but if it is an array you should do it like this

gameState(games)

Comments

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.