Next.js Discord

Discord Forum

Property 'map' does not exist on type 'PostData'

Answered
Atlantic salmon posted this in #help-forum
Open in Discord
Atlantic salmonOP
"use client";

import { useEffect, useState, FC } from "react";

interface PostData {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const apiUrl = "https://jsonplaceholder.typicode.com/posts/";

const Post: FC = () => {
  const [data, setData] = useState<PostData | null>(null);

  useEffect(() => {
    fetch(apiUrl)
      .then((res) => res.json())
      .then((res: PostData) => setData(res)) 
      .catch((error: Error) => {
        console.error("Error fetching data: ", error);
      });
  }, []);

  return (
    <div>
      <h2>gh</h2>
      {data ? (
        <div>
          {data.map((posts: any) => (
            <h1 key={data.id}>{data.body}</h1>
          ))}
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default Post;
Answered by joulev
since the endpoint returns an array of PostData, it should be PostData[] not PostData
View full answer

3 Replies

@Atlantic salmon "use client"; import { useEffect, useState, FC } from "react"; interface PostData { userId: number; id: number; title: string; body: string; } const apiUrl = "https://jsonplaceholder.typicode.com/posts/"; const Post: FC = () => { const [data, setData] = useState<PostData | null>(null); useEffect(() => { fetch(apiUrl) .then((res) => res.json()) .then((res: PostData) => setData(res)) .catch((error: Error) => { console.error("Error fetching data: ", error); }); }, []); return ( <div> <h2>gh</h2> {data ? ( <div> {data.map((posts: any) => ( <h1 key={data.id}>{data.body}</h1> ))} </div> ) : ( <p>Loading...</p> )} </div> ); }; export default Post;
"use client";

import { FC, useEffect, useState } from "react";

interface PostData {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const apiUrl = "https://jsonplaceholder.typicode.com/posts/";

const Post: FC = () => {
  const [data, setData] = useState<PostData[] | null>(null);

  useEffect(() => {
    fetch(apiUrl)
      .then(res => res.json())
      .then((res: PostData[]) => setData(res))
      .catch((error: Error) => {
        console.error("Error fetching data: ", error);
      });
  }, []);

  return (
    <div>
      <h2>gh</h2>
      {data ? (
        <div>
          {data.map(post => (
            <h1 key={post.id}>{post.body}</h1>
          ))}
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default Post;
since the endpoint returns an array of PostData, it should be PostData[] not PostData
Answer
Atlantic salmonOP
Dam thank you