Using Redux and Next.js and getting "store.getState is not a function"

42 Views Asked by At

I've set up my _app.js and store.js in what seems to be the expected format. This is my first attempt as using both so if I'm missing something obvious, please let me know.

store.js:

import { configureStore } from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';
import authReducer from '../store/slices/authSlice';
import searchReducer from '../store/slices/searchSlice';

const makeStore = () => {
    console.log('config store: ', configureStore({ reducer: { auth, search } }));
    return configureStore({
      reducer: {
        auth: authReducer,
        search: searchReducer,
      },
    });
}

export const wrapper = createWrapper(makeStore, { debug: process.env.NODE_ENV === 'development' });

_app.js:

import { Provider } from 'react-redux';
import { wrapper } from '../store/store';
function MyApp({ Component, pageProps }) {
  console.log('wrapper: ', wrapper);
  return (
    <Provider store={wrapper}>
      <Component {...pageProps} />
    </Provider>
  );
}

export default MyApp;

The console.log of my wrapper is:

wrapper:  {
  getServerSideProps: [Function: getServerSideProps],
  getStaticProps: [Function: getStaticProps],
  getInitialAppProps: [Function: getInitialAppProps],
  getInitialPageProps: [Function: getInitialPageProps],
  withRedux: [Function: withRedux],
  useWrappedStore: [Function: useWrappedStore]
}

The reason I've done all this is because I was originally getting a legacy error when using withRedux so it said I had to use the createWrapper option.

I've tried to look up on here and on ChatGPT and Gemini and nothing seems to explain why I'm getting TypeError: store.getState is not a function. It also looks like makeStore is never getting called because the console.log in the function never logs.

1

There are 1 best solutions below

1
Drew Reese On

The wrapper returns functionality that you need to use first before you can access the store. You are passing wrapper directly as the store.

See wrapper usage.

  • Using the useWrappedStore hook:

    import { Provider } from 'react-redux';
    import { wrapper } from '../store/store';
    
    function MyApp({ Component, pageProps }) {
      const { store, props } = wrapper.useWrappedStore(pageProps);
    
      return (
        <Provider store={store}>
          <Component {...props} />
        </Provider>
      );
    }
    
    export default MyApp;
    
  • Using the withRedux Higher Order Component:

    import { Provider } from 'react-redux';
    import { wrapper } from '../store/store';
    
    function MyApp({ Component, pageProps }) {
      return (
        <Component {...props} />
      );
    }
    
    export default wrapper.withRedux(MyApp);