I am attempting to access the state of redux-toolkit in Next.js's getStaticProps
(After saving the accessToken in the store, I need to access the store from getstaticprops for the API it requires)
Here's what I have tried:
export default function Page({ state }) {
console.log(state)
return <>...</>
}
export const getStaticProps = wrapper.getStaticProps((store) => {
return async () => {
const state = store.getState()
return {
props: {
state
}
}
}
})
I was able to successfully access the state and checked it on Redux DevTools where it appeared as the initial (empty) state.
redux devtools.img
console.log.img
This is my redux toolkit setup on Next.js
//_app.js
import { wrapper } from '../store'
function MyApp({ Component, pageProps }) {
axios.defaults.withCredentials = true
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default wrapper.withRedux(MyApp)
/store/index.js
import { configureStore } from '@reduxjs/toolkit'
import { createWrapper } from 'next-redux-wrapper'
import logger from 'redux-logger'
import reducer from './modules'
const makeStore = (context) =>
configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(/*logger*/),
devTools: process.env.NODE_ENV !== 'production'
})
export const wrapper = createWrapper(makeStore, {
debug: process.env.NODE_ENV !== 'production'
})
/store/modules/index.js
import { combineReducers } from '@reduxjs/toolkit'
import { HYDRATE } from 'next-redux-wrapper'
import timer from './timer'
import user from './user'
import cart from './cart'
const reducer = (state, action) => {
if (action.type === HYDRATE) {
return {
...state,
...action.payload
}
}
return combineReducers({
user,
timer,
cart
})(state, action)
}
export default reducer
/store/modules/user.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = { userInfo: null, token: null, address: null }
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
getNewToken: (state, action) => {
state.token = action.payload
},
getUserInfo: (state, action) => {
state.userInfo = action.payload
},
getAddress: (state, action) => {
state.address = action.payload
}
}
})
export const { getUserInfo, getNewToken, getAddress } = userSlice.actions
export default userSlice.reducer