I am completely lost on redux and next.js. I can't seem to figure out how to just simply connect the two after many frustrating hours. My site returns an error "TypeError: Cannot read property 'getState' of undefined". For some reason the store doesn't seem to have a valid reducer.
The following is the code that seems to be the problem. _app.js
import "../styles/globals.css";
import { SessionProvider } from "next-auth/react";
import store from "../store";
import { Provider as ReduxProvider } from "react-redux";
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<ReduxProvider store={store}>
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
</ReduxProvider>
);
}
export default MyApp;
store.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./slices/counterSlice";
export const store = configureStore({
reducer: { counter: counterReducer },
});
counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
value: 0,
};
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value = action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
all I am looking for is the site to not break. I just want to be able to play around with global state to change one variable from true to false and vice versa across different components.
Your store
is undefined
because it's not being imported correctly. Right now it's being exported from store.js
as a named export (not default
), so during import you'll need to remember to use curly braces:
_app.js:
// don't forget the curly braces around `store`
import { store } from "../store";
Alternatively, if your intention is to import the default
(so you can use a name other than store
), remember to specify the store
module's default
export:
store.js:
const store = configureStore({
reducer: { counter: counterReducer },
});
// `store` can be named something else during import (and no curly braces needed)
export default store;