Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Redux store in getServerSideProps in NextJS

I want to access my redux store in the getServerSideProps(); in my Next.js app. I want to have the user id which i'm storing in the Redux Store so i can preload user data. I'm now using next-redux-wrapper and on the client side it's working. But when i access my store in getServerSideProps() it returns the initial state. I checked several examples but i can't get it working.

My configureStore.js

import { createStore, applyMiddleware, compose } from "redux";
import reducer from "./../service";
import thunk from 'redux-thunk'
import { createWrapper, HYDRATE} from 'next-redux-wrapper';

const SET_CLIENT_STATE = 'SET_CLIENT_STATE';

const storeEnhancers = typeof window != 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const makeStore = ({ isServer }) => {

  if (isServer) {

    return createStore(reducer, storeEnhancers(applyMiddleware(thunk)) );

  } else {

      const { persistStore, persistReducer } = require('redux-persist');
      const storage = require('redux-persist/lib/storage').default;

      const persistConfig = {
          key: 'nextjs',
          whitelist: ['userReducer'],
          storage
      };

      const store = createStore(
        persistReducer(persistConfig, reducer),
        storeEnhancers(applyMiddleware(thunk))
      );
  
      store.__PERSISTOR = persistStore(store);

      return store;
  }
};

export const wrapper = createWrapper(makeStore);

export const setClientState = (clientState) => ({
  type: SET_CLIENT_STATE,
  payload: clientState
});

My _app.js:

import React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import theme from '../styles/theme';
import { useStore } from "react-redux";
import { PersistGate } from 'redux-persist/integration/react';
import {wrapper} from './../redux/configureStore';

const MyApp = ({Component, pageProps}) => {
  const store = useStore((state) => state);

  React.useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>Deeltuinen</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
        <PersistGate persistor={store.__PERSISTOR} loading={null}>
          <ThemeProvider theme={theme}>
            <CssBaseline />
            <Component {...pageProps} />
          </ThemeProvider>
        </PersistGate>
    </React.Fragment>
  );
}

export default wrapper.withRedux(MyApp);

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  pageProps: PropTypes.object.isRequired
};

And finally the page where i want to get the store state:

import React from 'react';
import Layout from './../../components/Layout';
import API from './../../service/api';
import {connect} from "react-redux";
import {wrapper, setClientState} from './../../redux/configureStore';

const AccountSettings = ({data}) => {
 
  return (
    <Layout title="Deeltuinen">
      // User form
    </Layout>
  );
}

export const getServerSideProps = wrapper.getServerSideProps(
  ({store, req, res}) => {
    const state = store.getState();
    console.log(state);

    //const data = await API.getUser(state.userReducer.user.token);
  }
);

export default connect(state => state,{setClientState})(AccountSettings);
like image 751
Emke Avatar asked Nov 27 '22 13:11

Emke


1 Answers

My Code:

export const getServerSideProps = wrapper.getServerSideProps(async ({ req, res, store }) => {
  const state = store.getState();
  console.log('state', state);

  return {
    props: {},
  };
});
`
like image 59
Jerry Avatar answered Nov 29 '22 05:11

Jerry