I'm using redux-persist for my e-commerce project.
When I updated my app to new version I found a new bug.
I changed my initialState from array into object.
My app in Chrome (browser that i test and run my app on it) crashed !! because my initialState still array(NOT UPDATE) and new method was not returned anything. (Of course).
But in Mozilla and other Browsers that I not use before them my app working currently !
why!?
My Store Config :
import { createStore, applyMiddleware } from 'redux'
import { persistStore } from 'redux-persist'
import logger from 'redux-logger'
import RootReducer from './RootReducer'
const middleware = [logger]
export const store = createStore(RootReducer, applyMiddleware(...middleware))
export const persistore = persistStore(store)
My rootReducer Config :
import { combineReducers } from 'redux'
import { persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import UserReducer from './User/UserReducer'
import ShoppingBagDropdownReducer from './ShoppingBagDropdown/ShoppingBagDropdownReducer'
import DirectoryReducer from './Directory/DirectoryReducer'
import ShopDataReducer from './ShopData/ShopDataReducer'
const persistConfig = {
key: 'root',
storage,
whileList: ['shoppingBagDropdown']
}
const rootReducer = combineReducers({
user: UserReducer,
shoppingBagDropdown: ShoppingBagDropdownReducer,
shopData: ShopDataReducer,
directory: DirectoryReducer
})
export default persistReducer(persistConfig, rootReducer)
Yeah :)
I found solution and that is : clear local storage with :
localStorage.clear();
I saw that you fixed it, but you could also do it without code using google chrome.
CTRL + SHIFT + I > Application > Local Storage
Now you just have to open the localstorage, right click and click on clear.
Related
I'm wondeirng is there a original, and most used way to code "Way to keep logged in state".
Currently, I set log in button to 'MyPage' button after successful logged in.
However, i referesh the web, then this state has gone.
Ah, i'm using React, and using Cookies with Access and Refresh Token, and wondering "Should i use another state to keep logged in information or not."
Before, i used localStorage and set the state manually, such as "isLogin" : "true" state in localStorage.
However, i'm wondering the way to use accessToken which expires automatically in 30 mins.
Will there ve a neat way to construct this function?
Thanks !
Do you want to log in again after the relaunch of the browser?
If so, it can be done with Redux store.
Here is the link for documentation.
https://redux.js.org/api/store
If not, it should be done with session or chrome.storage or something.
You can use redux-persist in your application so that state is maintained even if you are refreshing page after logged in application.
Sample redux store configuration:
import { combineReducers} from 'redux';
import { configureStore } from '#reduxjs/toolkit';
import thunk from 'redux-thunk';
import { persistReducer } from 'redux-persist';
import storage from '#/redux/sync_storage';
import { setupListeners } from '#reduxjs/toolkit/dist/query';
import persistStore from 'redux-persist/lib/persistStore';
import app from '#/redux/slice/appSlice';
const persistConfig = {
key: 'root',
storage,
//blacklist: ['app']
}
const rootReducer = combineReducers({
app,
})
const initialState = {}
const persistedReducer = persistReducer(persistConfig, rootReducer)
const store= configureStore({reducer:persistedReducer,initialState,devTools: process.env.NODE_ENV !== 'production',middleware:[thunk]})
setupListeners(store.dispatch);
export const persistor = persistStore(store, {}, () => {
persistor.persist();
});
export default store;
The below urls will help with the configuration for react application
https://www.npmjs.com/package/#reduxjs/toolkit
https://www.npmjs.com/package/redux-persist
https://kandi.openweaver.com/javascript/rt2zz/redux-persist#Code-Snippets
It is a MERN eCommerce Web Application. Why the page is blank(white screen) and What is the error in the console?
I have provided a screenshot(linked as My Web App in the browser) of my browser where you can see the white screen and an error. The error is pointing towards the code that I have written as the code below.
My Web App in browser
Code in store.js file
import {combineReducers, applyMiddleware } from "redux";
import {configureStore} from '#reduxjs/toolkit'
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import {
newProductReducer,
newReviewReducer,
productDetailsReducer,
productReducer,
productReviewsReducer,
productsReducer,
reviewReducer,
} from "./reducers/productReducer";
const reducer = combineReducers({
products: productsReducer,
productDetails: productDetailsReducer,
newReview: newReviewReducer,
newProduct: newProductReducer,
product: productReducer,
productReviews: productReviewsReducer,
review: reviewReducer,
});
const middleware = [thunk];
const store = configureStore(
reducer,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
I have an app that have different access level, like admin, guest and normal user, so it has several roles. My folder structure is very clear, some components are shared like Button, Loader but reducers and actions are not shared, because they are completely different of apps.
I did this to do conditioning setting for my store (Yes I only need one store because the entry for all type of the user is the same)
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
import userReducers from './reducers'
import adminReducers from './reducers/admin'
//share reducer btw member and admin
let reducers
if (getUserRole() === 'member') {
reducers = userReducers
} else {
reducers = adminReducers
}
console.log('reducers', reducers) //undefined during the first load, most likely store is done setup before localstorage?
const store = createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
export default store
The problem is reducers is undefined unless I refresh the entire page.
Maybe the problem is that localStore is not async according to this SO answer.
So by returning a Promise you'll make sure getUserRole() is not undefined:
export function getUserRole(){
return new Promise((resolve, reject) => {
let role = localStorage.getItem('token').decode('role')
resolve(role)
})
}
and in index.js:
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
import userReducers from './reducers'
import adminReducers from './reducers/admin'
//share reducer btw member and admin
let store
getUserRole().then(role => {
reducers = role === 'member'
? userReducers
: adminReducers
console.log('reducers', reducers)
store = createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
})
export default store
Tell me if something went wrong.
In my app on log out I'm doing this.props.dispatch(setUserSession({})) even passed null here. After dispatching in redux-logger I can see that it's changed to
action {type: "SET_USER_SESSION", userSession: {}}
next state {userSession: {}
But in local storage, I can still see the userSession that was there before dispatching null.
On what action or when will the persisted store will get updated.
I'm setting userSession to null on logout, but when the user refreshes the page, he is back in without login since the token is present in the store.
And also I don't want to do a purge or flush the full store, just that userSession key.
Current store configuration
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import reducer from './reducers';
let middleware = [thunk];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const configureStore = composeEnhancers(applyMiddleware(...middleware))(createStore);
const config = {
key: 'root',
storage
};
const combinedReducer = persistReducer(config, reducer);
const store = configureStore(combinedReducer);
const persistor = persistStore(store);
export { persistor, store };
Kindly provide some help, correct me if I'm missing something.
I have followed the guide here: https://redux-observable.js.org/docs/basics/SettingUpTheMiddleware.html (Section: Redux DevTools)
The store is configured in the following manner:
// #flow
import { createStore, compose, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { createReducer } from './reducer';
import { epic } from './epic';
const initialState = {};
const configureStore = () => {
const epicMiddleware = createEpicMiddleware(epic);
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancers = composeEnhancers(applyMiddleware(epicMiddleware));
const store = createStore(createReducer(), initialState, enhancers);
return store;
};
export { configureStore };
However, my React Application (bootstrapped with CRA) will not work if I don't have the Redux Devtools Extension installed.
Can someone please tell me what it is that I am doing incorrectly?
Error log on missing extension: https://pastebin.com/qzcbXCYQ
EDIT: I am an idiot. The store was defined in two files, and I was not changing the one where I was importing it from. Cleaned up the duplicates, and it is working as expected.
To make things easier, you can use the redux-devtools-extension package from npm.
To install it run:
npm install --save-dev redux-devtools-extension
and to use like so:
// #flow
import { createStore, compose, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { createReducer } from './reducer';
import { epic } from './epic';
import { composeWithDevTools } from 'redux-devtools-extension';
const initialState = {};
const configureStore = () => {
const epicMiddleware = createEpicMiddleware(epic);
const enhancers = composeEnhancers(applyMiddleware(epicMiddleware));
const store = createStore(createReducer(), initialState, composeWithDevTools(
applyMiddleware(epicMiddleware),
// other store enhancers if any
));
return store;
};
export { configureStore };
I was experiencing a similar issue. I just needed to tweak a single line. I went from this:
const composeEnhancers = !__PROD__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
To this:
const composeEnhancers = !__PROD__ ? (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose) : compose
In my case I have the __PROD__ variable available, but tweak that to suit your situation. Logic remains the same.
This problem usually comes with browsers dont having redux-devtool (May occur in chrome incognito chrome also)
I think you should check with your composeEnhancers
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
}) : compose;
reference : https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
This problem usually comes with browsers dont having redux-devtool (May occur in chrome incognito chrome also)
compose(applyMiddleware(thunk), window.REDUX_DEVTOOLS_EXTENSION||compose)
it's Shoud be worked
or try another
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk"
import blogReducer from "./Reducer/blogReducer";
const store = createStore(
blogReducer,
compose(applyMiddleware(thunk), window._REDUX_DEVTOOLS_EXTENSION && window._REDUX_DEVTOOLS_EXTENSION() || compose));
export default store