NEXTJS: getServerSideProps not working into components

Viewed 24402

Below is the code located at "Pages/home.js". // localhost:3000/home

import axios from 'axios';
import Section1 from '../components/home-sections/section-1';

const Homepage = ({ show }) => {
    const Html = JSON.parse(show.response.DesktopHTML);
    const renderSection = () => {
        return Html.map((itemData,index)=>{
            return(<div key={index}>{itemData.DisplayName}</div>)
        })
    }

    return(
        <div>
            { renderSection()}
            <Section1 />
        </div>
    )
}

export const getServerSideProps = async ({ query }) => {
 
  try {
    const response = await axios.get(
      `https://api.example.com/getHomeSection?title=Section 1`
    );
    
    return {
      props: {
        show: response.data,
      },
    };
  } catch (error) {
    return {
      props: {
        error: error.error,
      },
    };
  }
};

export default Homepage;

Now same code I added into section-1.js and this file is located to "components/home-sections/section-1.js"

Now getServerSideProps is working fine in home.js, but in section-1.js it is not working.

Error: TypeError: show is undefined in section-1.js
2 Answers

getServerSideProps can only be exported from Page components. It will not be run on components imported into a page.

However, you could export a function from the component that returns the props, and call that function from the page's getServerSideProps function.

  1. Create a getServerSideProps function on the component.

    // @components/MyComponent.tsx
    import { GetServerSidePropsContext } from 'next';
    
    function MyComponent(props: IMyComponentProps) {
        return (<div>MyComponent</div>;)
    }
    
    MyComponent.getServerSideProps = async (context: GetServerSidePropsContext): Promise<{ props: IMyComponentProps }> => {
        return { props: { ... } };
    }
    
    export default MyComponent;
    
  2. In your page's getServerSideProps function, call the component's getServerSideProps function and merge the props from the component with the props from the page.

    // mypage.tsx
    import MyComponent from '@components/MyComponent';
    
    const Page: NextPageWithLayout = (props: IIndexPageProps) => {
        return <MyComponent />;
    }
    
    export async function getServerSideProps(context: GetServerSidePropsContext): Promise<{ props: IIndexPageProps }> {
        let componentServerSideProps = await MyComponent.getServerSideProps(context);
        let otherServerSideProps = { props: { ... } };
    
        return {
            props: {
                ...componentServerSideProps.props,
                ...otherServerSideProps.props
            }
        };
    }
    
Related