1

I'm using next-redux-wrapper and dispatching actions from getServerSideProps from individual pages. But I realized that I can't access the populated store state from another page. If I try to, in either client-side or server-side, the state returns empty in the other pages.

So, I heard that using getInitialProps is required to share state among all pages. Since I'm getting confused with all these I want to have some doubts cleared. I want to know:

  1. When is it necessary, if at all, to use getInitialProps in the _app.js file when using redux with next-redux-wrapper? I heard that need to use getInitialProps inside _app.js in order to make the state accessible to every pages. But it's not working for me. Maybe due to wrong implementation!

  2. If I use getInitialProps in _app.js then, is it not required to use getServerSideProps or getStaticProps in individual pages?

  3. After populating state with getServerSideProps, can I share the state to every page without using getInitialProps in _app.js or if nneded can I pass the fetched state to getInitialProps in _app.js?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
forest
  • 1,312
  • 3
  • 20
  • 47

1 Answers1

0

Yes, You have to use getIntitprops in the APP component to provide store in all pages in this case all page will run on a server which huge downfall, if you have lots of static pages,

or you can use this code on each page according to your needs but your dispatch will change server-side state only!!!, which means you can access them on the client-side.

export const getServerSideProps = wrapper.getServerSideProps(async ({ store, query }) => {
    try {
        const { id } = query
        const res = await api.get('/abc', { params: { id } })
        await store.dispatch(action)
        return {
            props: {
                id,
                data: res.data,
                isServer: typeof window === 'undefined',
            }
        }
    } catch (error) {
        return {
            props: {
                errorCode: 409,
                message: "Data Unavailable"
            }
        }
    }
})

In the end, I ditched both options because it provides a bad user experience.

My recommendation is to use getInitProps and check if the page is rendering on the server then call API and save props in client-side, otherwise call API in the client a and save it.

Satyamskillz IN
  • 97
  • 2
  • 12