Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

reactjs - NextJS, preload Redux data in getServerSideProps

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...