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:
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!
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;