1

mates. I have a Menu Component in my next.js web app. The data of the menu come dynamically through GraphQL. I want server-side rendering for the menu component. I have tried to use getStaticProps() to render the data on the server. But getStaticProps() does not work on the component, it's only working on the page.

Now, how can I solve this problem? I don't want to duplicate the same code for the menu on every page, I want to re-use the code or something like that. Please help me to get rid of this problem. Thanks in advance.

Here is my code for menu rendering:

export async function getStaticProps() {

    const client = new ApolloClient(
        {uri: 'http://portfolio.local/graphql', cache: new InMemoryCache()}
    );

    const {data} = await client.query({

    query:gqlquery
        MyQuery{
            menuItems {
                edges {
                    node {
                        id 
                        label
                    }
                }
            }
        }

    });

    return {

        props: {

            menus: data.menuItems.edges

        }

    }

}

1 Answer 1

0

Why don't you call your data straight in the front end? Without 'getStaticProps' or 'getServerSideProps' As you said, it's a menu, so the data doesn't matter for SEO.

function MenuComp() {
const [data, setData] = React.useState()
  
React.useEffect(async ()=>{
  const client = new ApolloClient(
        {uri: 'http://portfolio.local/graphql', cache: new InMemoryCache()}
    );

    const {data} = await client.query({

    query:gqlquery
        MyQuery{
            menuItems {
                edges {
                    node {
                        id 
                        label
                    }
                }
            }
        }

    });
   setData(data)
},[])

return (...your component)
}

4
  • Yes, Menu does not matter for SEO. But I want to learn, I want to know if is there any option to do this. Commented Mar 10, 2021 at 16:41
  • getServerSideProps and getStaticProps can only be exported from a page. So you cannot use them to get data for a dynamic menu component. I think you could link the menu to your persistent layout component and fetch data on the client-side Commented Mar 11, 2021 at 18:38
  • Thank You. If I use getInitialProps() in _app.js to render the menu it's work perfectly. And maybe it's also SSR. But I don't know is it a good practice or not. Am I on the right path? Commented Mar 12, 2021 at 19:17
  • getInitialProps is not recommended way to fetch data in Next JS. For sure is SSR otherwise is not dynamic. I would stick to my option to fetch the data directly on the front end. I don't see the use of SSR. Commented Mar 18, 2021 at 16:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.