简体   繁体   中英

error - TypeError: Cannot read properties of undefined (reading 'getState') while using redux store in next.js

Just came across this issue error - TypeError: Cannot read properties of undefined (reading 'getState') with next.js and redux.

在此处输入图像描述

Here is my code below, I don't know the reason why I am facing this issue.

pages/app/store.js

import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "../slices/counterSlice";

export const store = configureStore({
    reducer: {
        counter : counterSlice
    }
});

pages/slices/counterSlicer.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    count : 0
};

export const counterSlice = createSlice({
    name : "counter",
    initialState,
    reducers: {
        increment : (state , action) => {
            state.count += 1;
        }
    }
});

export const { increment } = counterSlice.actions;

export const getCount = (state) => state.counter.count;

export default counterSlice.reducer;

I never had dispatched any action yet, maybe dispatch later

pages/_app.js

import '../styles/globals.css'
import { Provider } from 'react-redux';
import { store } from '@reduxjs/toolkit';

function MyApp({ Component, pageProps }) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  )
}

export default MyApp;

and finally in pages/index.js

import styles from '../styles/Home.module.css'
import { useSelector } from 'react-redux'
import { getCount } from './slices/counterSlice'

export default function Home() {
  const value = useSelector(getCount);
  return (
    <div className={styles.container}>
      The value is {value}
     </div>
  )
}

Note: For more info let me tell you that I have tried the exact code in react app also, but the same code is working in react but not working in next.js

You can check the output of react in this image

在此处输入图像描述

You need to wrap props.

Please see this https://github.com/kirill-konshin/next-redux-wrapper/blob/master/packages/demo-redux-toolkit/pages/_app.tsx

Export wrapper from your store.js

import { createWrapper } from 'next-redux-wrapper';
...
export const wrapper = createWrapper(makeStore);

And your _app.js should be

 import '../styles/globals.css' import { Provider } from 'react-redux'; import { wrapper } from './store'; function MyApp({ Component, ...rest }) { const { store, props } = wrapper.useWrappedStore(rest); return ( <Provider store={store}> <Component {...props} /> </Provider> ); } export default MyApp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM