risky last
risky last

Reputation: 475

Property '...' is missing in type 'ReactElement<any, any>' but required in type '{...}'

I am new to TypeScript and am trying to render a page by getting data from getStaticProps using the following code:

import React, {FormEvent, useState} from "react";
import { InferGetStaticPropsType } from "next";
import AddPost from '../components/AddPost';
import Post from "../components/Post";
import { IPost } from "../types";

const API_URL: string = 'https://jsonplaceholder.typicode.com/posts'

export default function IndexPage ( {
    posts
}) : InferGetStaticPropsType<typeof getStaticProps> {
    const [postList, setpostList] = useState(posts);

    if(!postList) {
        return <h1>Loadin....</h1>
    } 

    return (
        <div>
            <h1>My posts</h1>
            {postList.map((post : IPost) => {
                <div>
                    <h1>post{post.id}</h1>
                    <Post key={post.id} post={post}
                </div>
            })}
        </div>
    )

}

export async function getStaticProps() {
    const res = await fetch(API_URL)
    const posts : IPost[] = await res.json()

    return {
        props: {
            posts
        }
    }
}

My post type is defined as:

export interface IPost {
    id: number
    title: string
    body: string
  }

The code executes fine but I get a ts error saying when trying to return the jsx to render on the screen:

Property 'posts' is missing in type 'ReactElement<any, any>' but required in type '{ posts: IPost[]; }'.

Could You please help me with what's wrong here?

Upvotes: 0

Views: 1710

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 46261

You seem to be typing incorrectly. I would suggest you to type IndexPage with FC from React as the page is a React Functional Component, like this:

import { FC } from "react";
const IndexPage: FC<{ posts: IPost[] | null }> = ({ posts }) => {
  return <div></div>;
};
export default IndexPage;

Also your map part is not correct as you are not returning anything and also not adding the key:

{postList.map((post: IPost) => {
  return (
    <div key={post.id}>
      <h1>post{post.id}</h1>
      <Post key={post.id} post={post}
    </div>
  );
})}

Upvotes: 2

Related Questions