skip to Main Content

I am trying to render some data on the console that is being brought in from my route handler.

Here in /api/pokemon/route.tsx

export async function GET() {
  const result = await fetch('https://pokeapi.co/api/v2/pokemon?limit=151');
  const data = await result.json();
  return Response.json({ data });
}

When I visit http://localhost:3000/api/pokemon, I see the following:

enter image description here

However, where I am fetching that data in my Pokelist component, the console log shows undefined.

/components/Pokelist.jsx

import { Pokemon } from '@/app/types/pokemon';
import React from 'react';

export async function getPokemon() {
  const pokemon = await fetch('http://localhost:3000/api/pokemon', {
    next: {
      revalidate: 30,
    },
  });
  const data = await pokemon.json();
  return data.status;
}

const Pokelist = () => {
  const pokemonItems = getPokemon();
  console.log('data:', pokemonItems);
  return <></>;
};

export default Pokelist;

Anyone know why the data is showing in my browser, but it is undefined on the server side when I try to console log and fetch the data in my Pokelist component? Thanks!

2

Answers


  1. A couple of things stand out:

    • const pokemonItems = getPokemon();

      You are not awaiting this Promise, this will not return any data and just print out the Promise object. You can do something like this to wait for the promise to finish:

      useEffect(() => {
        const fetchData = async () => {
          const data = await getPokemon();
          console.log(data);
        };
      
        fetchData();
      }, []);
      
    • return data.status;

      This should probably be: return data;

    Login or Signup to reply.
  2. In order to use the results of this promise, we need to add the use of state into the component in order to allow dynamic updates. One way to do this would be to use the native useState and useEffect React hooks. For example,

    import { Pokemon } from '@/app/types/pokemon';
    import React, { useEffect, useState } from "react";
    
    export async function getPokemon() {
      const pokemon = await fetch('http://localhost:3000/api/pokemon', {
        next: {
          revalidate: 30,
        },
      });
      const data = await pokemon.json();
      return data.status;
    }
    
    const Pokelist = () => {
      const [pokemonItems, setPokemonItems] = useState([]);
      useEffect(async () => {
        setPokemonItems(await getPokemon());
      }, []);
      console.log('data:', pokemonItems);
      // You can then map the results of pokemonItems in this component
      return <></>;
    };
    
    export default Pokelist;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search