0
votes

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

1 Answers

0
votes

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)
}