The the official Redux Toolkit docs recommend typing the RootState
as follows:
import { configureStore } from '@reduxjs/toolkit'
// ...
export const store = configureStore({
reducer: {
posts: postsReducer,
comments: commentsReducer,
users: usersReducer,
},
})
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
However, when using Redux with server-side rendering (SSR) framework like Gatsby, I need to export my configureStore call as a callable function, so I can be sure it is only instantiated once:
import { configureStore } from '@reduxjs/toolkit'
// ...
// 'store' is recommended by the gatsby team to be a function,
// See https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/wrap-with-provider.js
export const store = () => configureStore({
reducer: {
posts: postsReducer,
comments: commentsReducer,
users: usersReducer,
},
})
// TODO: won't work because store is not a const anymore, it is a function!
// Infer the `RootState` and `AppDispatch` types from the store itself
// export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
// export type AppDispatch = typeof store.dispatch
anybody know how I can reconcile keeping the configure store call a function (to follow Gatsby best practices), yet still getting the RootState
type out somehow (so I can use things like useSelector
throughout my app)?