Reputation: 14811
Today my AppDispatch
type is extracted from store.dispatch
:
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import auth from "./auth/authSlice";
const rootReducer = combineReducers({ auth });
const store = configureStore({
reducer: rootReducer
});
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export default store;
Now I try to replace store with initStore function. I want to rehydrate my store using preloadedState.
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import auth from "./auth/authSlice";
const rootReducer = combineReducers({ auth });
const store = (preloadedState={}) => {
return configureStore({
reducer: rootReducer,
preloadedState,
});
}
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export default store;
I have an error:
Property 'dispatch' does not exist on type '(preloadedState?: {}) => EnhancedStore<CombinedState<{ auth: AuthState; }>, AnyAction, [ThunkMiddleware<CombinedState<{ auth: AuthState; }>, AnyAction, null> | ThunkMiddleware<...>]>'.ts(2339)
How can I get the AppDispatch type correctly ?
Upvotes: 3
Views: 4186
Reputation: 67539
You've changed store
from being an actual Redux store instance to "a function that returns a Redux store", without fixing the rest of your code to match that. So, the first issue is that typeof store.dispatch;
won't work at that point in the code, because store
is a function and not an actual store instance.
Beyond that, I'm not sure how you'd actually manage to get the type of dispatch
here because you haven't created a store yet when the type is being defined. I suppose you could try something like this, but I don't know if it'll work:
const initStore = (preloadedState={}) => {
return configureStore({
reducer: rootReducer,
preloadedState,
});
}
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = ReturnType<typeof initStore>["dispatch"];
export default initStore ;
Upvotes: 4