Search code examples
tsxreact-tsx

Rawg not returning results


I am learning react and I am following a tutorial in which I have to do this project. I need to use the Rawg API to fetch games and display them, but right now it returns undefined. I have tried using PostMan to see what the response is, and it gives me the results there.

Here is my code for App.tsx:

import { Button, Grid, GridItem, Show } from "@chakra-ui/react";
import React from "react";
import NavBar from "./components/NavBar";
import GameGrid from "./components/GameGrid";

const App = () => {
  return (
    <Grid
      templateAreas={{
        base: `"nav" "main"`,
        lg: `"nav nav" "aside main"`,
      }}
    >
      <GridItem area="nav">
        <NavBar></NavBar>
      </GridItem>
      <Show above="lg">
        <GridItem area="aside">Aside</GridItem>
      </Show>
      <GridItem area="main">
        <GameGrid></GameGrid>
      </GridItem>
    </Grid>
  );
};

export default App;

GameGrid.tsx:

import { useState, useEffect } from "react";
import apiClient from "../services/api-client";
import { ListItem, UnorderedList } from "@chakra-ui/react";

interface Game {
  name: string;
  id: number;
}

interface FetchGamesResponse {
  count: number;
  result: Game[];
}

const GameGrid = () => {
  // Setup variables
  const [games, setGames] = useState<Game[]>([]);
  const [error, setError] = useState("");

  // Get games from backend
  useEffect(() => {
    apiClient
      .get<FetchGamesResponse>("/games")
      .then((res) => {
        console.log("??? - " + res.data.result);
        setTimeout(() => {
          console.log(res.data.result);
        }, 5000);
      })
      .catch((error) => {
        setError(error.message);
      });
  }, []);

  return (
    <>
      {error !== "" && <p>{error}</p>}
      <UnorderedList>
        {games ? (
          games.map((game) => <ListItem key={game.id}>{game.name}</ListItem>)
        ) : (
          <p>Loading...</p>
        )}
      </UnorderedList>
    </>
  );
};

export default GameGrid;

And lastly, api-client.ts:

import axios from "axios";

export default axios.create({
  baseURL: "https://api.rawg.io/api",
  params: {
    key: "My API key",
  },
});

I have checked that the API key has enough uses, and it has well over enough. My console.log statements both say that res.data.result is undefined, but Postman says it is not. Can someone help me out?


Solution

  • The reason that there was nothing at res.data.result, is because it is misspelled. You should write res.data.results instead.