skip to Main Content

I was trying to fetch my data from github using getStaticProps for more performance and it returns this error even when I do a "console.log" it returns me the array but I can’t map it so what am I missing

code:

"use client";

import { GetStaticProps } from "next";

interface PostGithubProps {
  posts: {
    name: string
  }[]
}

export default function Github({ posts }: PostGithubProps) {
  return(
    <>
     {posts.map(post => {
       <p key={post.name}>{post.name}</p>
      })}
    </>
  )
}

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch('https://api.github.com/users/{myuser}/repos')
  const posts = await res.json()

  return { 
    props: {
      posts
    }
  }
} 

So what am I missing to do this map works, as I already said on console return the array of repos from github.

2

Answers


  1. Chosen as BEST ANSWER

    In this new version of Next we don't need getStaticProps anymore my mistake 😅. I solve it like this:

    interface PostGithubProps {
      name: string
    }
    
    export default async function Github() {
      const response = await fetch(`https://api.github.com/users/{myuser}/repos`, {
        next: {
          revalidate: 60 * 60 * 24, // 24 hours
        },
      })
    
      const repositories = await response.json()
    
      return (
          {repositories.map((repos: PostGithubProps) => (
            <p key={repos.name}>
              {repos.name}
            </p>
           ))}
      )
    }
    

  2. It is because, on the initial render, your posts are not available so you must check for undefined value first something like this :

    import { GetStaticProps } from "next";
    
    interface PostGithubProps {
      posts: {
        name: string
      }[]
    }
    
    export default function Github({ posts }: PostGithubProps) {
      if(!posts) return <div>Loading...</div>;
      return(
        <>
         {posts.map(post => {
           <p key={post.name}>{post.name}</p>
          })}
        </>
      )
    }
    
    export const getStaticProps: GetStaticProps = async () => {
      const res = await fetch('https://api.github.com/users/{myuser}/repos')
      const posts = await res.json()
    
      return { 
        props: {
          posts
        }
      }
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search