Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
khaiquangnguyen opened this issue Aug 27, 2024 · 1 comment
Open

Comments

@khaiquangnguyen
Copy link

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!

@reduxjs reduxjs deleted a comment Aug 27, 2024
@markerikson
Copy link
Collaborator

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

@reduxjs reduxjs deleted a comment from lucky6894 Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants