Based on this info from the official NextJS docs they recommend using getServerSidedProps and getStaticProps instead of getInitialProps.
I want to preload some data to Redux state on the server.
note: I use @redux/toolkit package
So I have basic store setup:
import reducer from './reducer' // this is just a combineReducers ...
export const store = configureStore({ reducer });
My custom _app.js
import { store } from '../store'
<Provider store={store}>
<Component {...pageProps} />
</Provider>
Now here is the issue I am facing
In the index.js file i have something like this
import { store } from '../store'
...
export const getServerSideProps = async (ctx) => {
const data = await fetchSomeData();
// here I add some data to the store
store.dispatch(someAction(data));
return { props: {} }
}
Data is set in the store while on the server side, however when I am on the client, store is empty. Does anyone know how can I preload data while on the server? I don't want to use useEffect of componentDidMount and set that data on the client. I know there is a library that is fixing this issue, but it is using getInitialProps instead, and I would like to see if something can be done in this way.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…