简体   繁体   中英

How to set the preloadedState in redux toolkit (with typescript)?

At the moment I'm doing this

export let store = null;

export default function getStore(incomingPreloadState?: any) {
  store = configureStore({
    reducer: { 
      content: ContentSlice
    },
    preloadedState: incomingPreloadState,
  });
  return store;
}
export type AppState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

Obviously, I'm getting the error that the store could possibly be null

There's a lot more going on here. You probably don't want that module-global store variable that would always be "the last store created" - at least I wouldn't recommend that, as you could end up with mixing up multiple store instances that way.

To get the right type for the store, you'll have to call combineReducers manually.

const rootReducer = combineReducers({
  content: ContentSlice
})

export default function getStore(incomingPreloadState?: AppState) {
  const store = configureStore({
    reducer: rootReducer,
    preloadedState: incomingPreloadState,
  });
  return store;
}
export type AppState = ReturnType<typeof rootReducer>
export type AppDispatch = ReturnType<typeof getStore>['dispatch']

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