Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux-persist keeps on loading

Motivation

I'd like to keep user information on page refresh/redirect, but also I want to clear it after logout action.


Configuration

const rootReducer = combineReducers({productsReducer, auth: accessReducer, usersReducer});

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['auth']
};

I want to persist data only in accessReducer that's why it's whitelisted. Now I want to handle logout in such way that all data in reset. To do so I've created logoutReducer:

Logout reducer

export const logout = () => ({
    type: 'USER_LOGOUT'
});

const logoutReducer = (state, action) => {
    if(action.type = 'USER_LOGOUT'){
        state = undefined;
    }

    return rootReducer(state, action);
};

Store and persistor

const persistedReducer = persistReducer(persistConfig, logoutReducer);
export const store = createStore(persistedReducer, applyMiddleware(thunk));
export const persistor = persistStore(store);

PROBLEM

Once I run the application, I get loading information which comes from a <Loader/> in PersistGate:

<Provider store={store}>
    <PersistGate loading={<Loader/>} persistor={persistor}>
        ...
    </PersistGate>
</Provider>

POSSIBLE CAUSE

Now I guess it's because I pass logoutReducer which has only reference to other reducers and that's why configuration fails. How do I persist user information and keep that logout-clear-store trick? Is there any other solution for this? Any help would be appreciated ♥

like image 694
J.Kennsy Avatar asked Mar 06 '26 02:03

J.Kennsy


1 Answers

ANSWER

During doing research about this problem I've found this issue, where poster had similar problem. Solution is in the last comment in this post, that is: react-reset. Here is my application of this package to mentioned above problem:

const appReducer = combineReducers({productsReducer, auth: accessReducer, usersReducer});

const persistConfig = {
    key: 'root',
    storage,
    whitelist: ['auth']
};

const enHanceCreateStore = compose(
    applyMiddleware(thunk),
    reduxReset()
)(createStore);

const persistedReducer = persistReducer(persistConfig, appReducer);
export const store = enHanceCreateStore(persistedReducer);
export const persistor = persistStore(store);

Then you just simply on logout dispatch action given from redux-reset:

store.dispatch({
  type: 'RESET'
})
like image 103
J.Kennsy Avatar answered Mar 08 '26 17:03

J.Kennsy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!