1

If I write a new page.tsx in a folder e.g. src/app/parts/test i get all the time the error, that the Props are undefined.

Here my Code (it should work...) src/app/parts/test/page.tsx

import { NextPage, GetServerSideProps } from 'next';

interface Props {
    json: {
        products: object[];
    };
}

const Page: NextPage<Props> = (props) => {
    console.log(props.json);



    return (
        <>
            {props.json.products.map((item) =>{
                return <p key={item.id}>{item.title}</p>
            })}
        </>
    );
};

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
    try {
        const data = await fetch("https://dummyjson.com/products");
        const json = await data.json();

        return {
            props: { json }
        };
    } catch (error) {
        console.error("Error fetching data:", error);
        return {
            props: { json: { products: [] } }
        };
    }
};

export default Page;

here the console error:

undefined
undefined
- error src\app\parts\test\page.tsx (16:24) @ products
- error TypeError: Cannot read properties of undefined (reading 'products')
    at Page (./src/app/parts/test/page.tsx:12:30)
    at stringify (<anonymous>)
  14 |     return (
  15 |         <>
> 16 |             {props.json.products.map((item) =>{
     |                        ^
  17 |                 return <p key={item.id}>{item.title}</p>
  18 |             })}
  19 |         </>
- wait compiling /favicon.ico/route (client and server)...
- event compiled successfully in 148 ms (1014 modules)

I created the new page file in the test folder to check but even there this error happens

Carlo
  • 112
  • 5
  • It seems like the fetched data dosn't reach the component over the props. That at least indicates the on and of logging of the undefined in my console. – Carlo Aug 15 '23 at 12:30
  • And im not able to log inside the getServersideProps Function seems like its never run? – Carlo Aug 15 '23 at 12:30

1 Answers1

0

The app directory does not support getServerSideProps or any of the other data fetching methods.


Inside the app directory you will achieve your goal using server components. Inside them you can directly fetch the required data in an asynchronous manner, similarly as you would in the data fetching methods used inside the pages directory.

export default async function MyComponent() {
  const response = await fetch("https://exxample.com/api/hello"):
  const data = await response.json();
  return <pre>{data}</pre>;
}

I recommend you take a look at the documentation to learn more about the fundamentals of Next.js 13, the app directory and React 18.

Fabio Nettis
  • 1,150
  • 6
  • 18
  • Thank you very much :-) I had all the time the wrong documentation open i just noticed... :-) – Carlo Aug 15 '23 at 13:44