apinext.jsaxiosgetstaticprops

getStaticProps return an empty array


hi i'm trying to do a twitch clone with Nextjs,

i'm trying to fetch the twith api with what NextJs offer: getStaticProps so i wrote a code like this but it doesn't work, it return me an empty array and i don't understand why

here is my code :

type Props = {};

function Games({}: Props, props:any) {
console.log(props)

  return (
    <div>
    </div>
);
}

    export async function getStaticProps() {
        
        try {
            const url: string = "https://api.twitch.tv/helix/games/top";
            const resp = await api.get(url);
            const data = await resp?.data;
    
            return {
                props: {
                    data:data
                }
            }
        }
        catch(error){
            console.log(error)
        }
    }

the api variable is code like that :

import axios from 'axios'

let api = axios.create({
    headers:{
        'Client-ID': process.env.TWITCH_API_KEY,
        'Authorization' :`Bearer ${process.env.TWITCH_BEARER}`
    }
})

export default api

when i try with post man with the same url, client-id and bearer i got a response 200 with all of the top games so why it doesn't work with get static props?


Solution

  • You are not passing the data prop to the Games component. You are declaring that Games should require a data prop.

    Documentation: Next.JS/Data Fetching/getStaticProps

    Stripping the component down to bare bones, we get:

    export default function Games({ data }) {
      console.log(data);
      return <div>Games Component</div>;
    }
    
    export async function getStaticProps() {
      const data = res;
      return {
        props: {
          data: data,
        },
      };
    }
    

    Then in a page (where the component is rendered), we can pass data as such:

    import Games from "./games";
    
    export default function Page() {
      //mocked API response
      const responseData = [{ game1: "A Game" }, { game2: "Another Game" }];
    
      return (
        <div>
          <h1>Page</h1>
    // passing `data` to `Games`
          <Games data={responseData} />
        </div>
      );
    }
    

    Now the console log appears as expected.

    As an aside, I'd recommend rethinking the TypeScript implementation. You may want to remove the type declaration, since you also have an inline type declaration. You could also implement an interface, instead.