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.
getStaticProps(): A method that tells the Next component to populate props and render into a static HTML page at build time. getServerSideProps(): A method that tells the Next component to populate the props and render into a static HTML page at run time.
Redux is one of the most popular state management solutions in the React ecosystem. Nowadays, there are plenty of alternatives, but Redux is still the most trusted and widely used tool. For this reason, many projects that use Next. js want to take advantage of Redux as well.
getServerSidedProps
should be used if you need the data only while you're server-side rendering. But if you need the data there for both cases when the user starts from this page (where you fetch data on the server) as well as client-side navigates to the page, it would be better to use getInitialProps
to fetch data (via redux-toolkit
's createAsyncThunk
).
Anyway, with both getServerSidedProps
and getInitialProps
you need to pass the server-side store to the to the client be the initial client store. You might want to consider using next-redux-wrapper for this task. You can find a nice example here.
Furthermore, you're missing usage of react-redux
's connect
to mapStateToProps
and mapDispatchToProps
.
I'm using next.js
and react-redux
with similar configuration to yours and I was struggling with all the boilerplate code required to get store data and dispatch actions. So I've created connect-initial-props to make it much easier to user getInitialProps
to dispatch actions and consume state's data from redux store. You're welcome to take at the example on connect-initial-props Github.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With