getServerSideProps functions is not gettin called in NextJS 13

49 Views Asked by At

Here is my code, console.log(data) is undefined

i read the docs and also visited many blogs

i made sure that api endpoint is working

my page is under '/app/posts/page.js'

my AllPost function is running before my gerserversideprops function

getserversideprops function is never running, unless i call it manually after defining function. But it also not solving the error. I am still getting undefined console.log and i am not receiving any props

const AllPosts = ({ data }) => {
    console.log(data);          //undefined
    console.log("Hello");       //hello
    return (
        <div>
            {data.map((item) => {
                return (
                    <div key={item.name}>
                        <div>{item.name}</div>
                        <p>{item.email}</p>
                    </div>
                );
            })}
        </div>
    );
};

export async function getServerSideProps() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users");
        const data = await response.json();
        console.log(data);

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

        return { props: { data} };
    }
}


//getServerSideProps   // when i call the function manually, then this function get called, but my console.log is still undefined



export default AllPosts;

i have seen youtube videos and used exact code in my vs code but it is not working for me

1

There are 1 best solutions below

0
Ahmed Abdelbaset On

There is no getServerSideProps in the app directory. You can use it only in the pages directory.

In the app directory, you can directly write your server code in the server component.

const AllPosts = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await response.json();
    console.log(data);

    return (
        <div>
            {data.map((item) => {
                return (
                    <div key={item.name}>
                        <div>{item.name}</div>
                        <p>{item.email}</p>
                    </div>
                );
            })}
        </div>
    );
};

export default AllPosts