Home > front end >  In NextJS, how can I avoid repeating the getStaticProps function on every page?
In NextJS, how can I avoid repeating the getStaticProps function on every page?

Time:12-18

I'm new to React/NextJS so getting my had around it's capabilities regarding requiring/importing files etc.

I'm using getStaticProps for SSG, to pull data in from Prismic CMS.

As stated in the NextJS documentation:

getStaticProps can only be exported from a page. You cannot export it from non-page files, _app, _document, or _error. One of the reasons for this restriction is that React needs to have all the required data before the page is rendered.

In practice this means I'm repeatedly using the same function across many pages and templates of the site, in stark contradiction to DRY principles..

Is there any way that I can write this once in a single file and use it across multiple pages without breaking the NextJS/SSG functionality?

I've tried variations along the lines of the following to no avail:

// testfunc.tsx
const TestFunc = () => {
    return (

        async function getStaticProps() {        
            const client = createClient()
    
            const [menu, page] = await Promise.all([
                client.getSingle( 'menu' ),
                client.getSingle( 'page' ),
            ])
    
            return {
                props: {
                    menu,
                    page,
                },
            }        
        }    
    )
}
export default TestFunc;

// page.tsx
import TestFunc from './TestFunc'

CodePudding user response:

Actually, in Next.Js there are two types of rendering Static Site Generation (SSG) and Server Side Rendering (SSR). You can google the detailed difference but in short, when you work with SSG that means you are already aware of which data will be used to generate the HTML pages and you also need to implement the getStaticPaths function as well and this isn't new for the developer as we have been using this static pages from a long time.

So answer to your initial question if you are following SSG then yes you need to repeat this code on every page, so while building WebApp Next.JS will call these functions internally to get the data and will generate the HTML pages at build time so when you try to access any of these pages in the browser it will show page which is generated at build time, even your backend data is changed it will not be reflected on these pages so if you need updated data on it then you have to build the app again. Also if you go to the network tab you can see the entire HTML page as a response.

If you are sure that your data is static for all the pages then you can just write these functions in one helper file, and then export and import wherever you need it (which isn't a realistic scenario but I think for learning purposes it's ok).

I hope this answered your question, Happy Coding!

  • Related