redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

RTK, redux-persist, code splitting and initiate state compatibility

Open khaiquangnguyen opened this issue 1 year ago • 1 comments

I tried to make code splitting works with RTK 2.0 and redux-persist, and I initially started with this code

const rootReducerWithSlice = rootReducer.inject({
  reducerPath: NAME,
  reducer: persistReducer(PersistConfig, slice.reducer),
});

const selector = rootReducerWithSlice.selector;

const selectSomething = selector(state => ...)
persistor?.persist();

This supposely follows the pattern recommended by RTK, with the only exception being that the reducer is wrapped in a persistReducer function. However, when I tried to run this, selectSomething fails to take into account the initialState value and returns undefined. This works perfectly fine when persistReducer is reduced.

A hack(?) that I eventually use is to call store.replaceReducer(rootReducerWithSlice); right after rootReducerWithSlice is created, as this forces the store to load the initial state data. But it seems a bit hacky to me (since it is not in the official docs, though I do find it relatively simple and straightforward. It also removes the need to use rootReducerWithSlice, as the store state is already synced and updated. It also works for all split slices, since rootReducer.inject is updated by reference. This is so much more straightforward than using rootReducerWithSlice, almost to the point where I feel like I am missing something critical by using it ).

And I don't really understand why the original code fails either. I guess that persistReducer does something that makes rootReducerWithSlice fails to handle the initial state, but I don't really know if it is something coming from redux-persist or redux-toolkit.

Anyone can give me some insights on what the issue is, whether what I do is correct and if there's any issues that I don't see, and whether the issue above worths having a fix in either redux-toolkit or redux-persist.

Thanks a lot!

khaiquangnguyen avatar Aug 27 '24 14:08 khaiquangnguyen

Does this only occur if you're using a persisted reducer?

markerikson avatar Aug 30 '24 18:08 markerikson