I'm trying to get rehydrated redux-persist state in a react-router-dom loader, but am only getting initial state.
My index.tsx:
import store, { persistor } from "./store/store";
...
import Profile, { loader as profileLoader } from './components/Profile/Profile';
...
const router = createBrowserRouter([
{
path: "/",
element: <App />, // This should be the root route
errorElement: <Error />,
children: [
....
{
path: '/profile',
element: <Profile />,
loader: profileLoader
}
],
},
]);
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RouterProvider router={router} />
</PersistGate>
</Provider>
</React.StrictMode>
);
My store.tsx:
import { configureStore } from "@reduxjs/toolkit";
import { combineReducers } from "redux";
import { userReducer } from "./slices/userSlice";
import storage from "redux-persist/lib/storage";
import { persistReducer, persistStore } from "redux-persist";
const persistConfig = {
key: 'root',
storage,
debug: true
};
const rootReducer = combineReducers({
user: userReducer,
});
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
});
export const persistor = persistStore(store);
export default store;
My Profile.tsx:
import { useLoaderData } from 'react-router-dom';
import store from '../../store/store';
export async function loader() {
console.log(`loader: ${JSON.stringify(store.getState().user)}`);
return store.getState().user;
// GLOBAL STATE DOESN'T REHYDRATE TIL AFTER LOADERS RUN
// DON'T ACCESS GLOBAL STATE IN THE LOADER
}
export default function Profile() {
const globalState = store.getState().user;
console.log(`component: ${JSON.stringify(globalState)}`);
return (
<h1>{globalState.username}</h1>
);
}
By the time react-router-dom loads the data for the Profile route, I'm expecting Redux to be rehydrated. But here's what it actually is at that point in time, compared to accessing the same state in the functional component itself:
Based on the order of those logs, it seems like Redux rehydrates only after the loader runs. Is there any way to rehydrate Redux before the route loader runs? I am wrapping the router in a PersistGate, but that doesn't seem to be making the route loader wait for rehydration...
