I am using Redux for state management.
How do I reset the store to its initial state?
For example, let’s say I have two user accounts (u1 and u2).
Imagine the following sequence of events:
User u1 logs into the app and does something, so we cache some data in the store.
User u1 logs out.
User u2 logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers(). However, whenever it receives USER_LOGOUT action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer and write a new rootReducer delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer to return the initial state in response to the USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state as we pass it to appReducer:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
return appReducer(undefined, action)
}
return appReducer(state, action)
}
In case you are using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and the state copy will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
// for all keys defined in your persistConfig(s)
storage.removeItem('persist:root')
// storage.removeItem('persist:otherKey')
return appReducer(undefined, action);
}
return appReducer(state, action);
};
Dan Abramov's answer is correct except we experienced a strange issue when using the react-router-redux package along with this approach.
Our fix was to not set the state to undefined but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
Define an action:
const RESET_ACTION = {
type: "RESET"
}
Then in each of your reducers assuming you are using switch or if-else for handling multiple actions through each reducer. I am going to take the case for a switch.
const INITIAL_STATE = {
loggedIn: true
}
const randomReducer = (state=INITIAL_STATE, action) {
switch(action.type) {
case 'SOME_ACTION_TYPE':
//do something with it
case "RESET":
return INITIAL_STATE; //Always return the initial state
default:
return state;
}
}
This way whenever you call RESET action, you reducer will update the store with default state.
Now, for logout you can handle the like below:
const logoutHandler = () => {
store.dispatch(RESET_ACTION)
// Also the custom logic like for the rest of the logout handler
}
Every time a userlogs in, without a browser refresh. Store will always be at default.
store.dispatch(RESET_ACTION) just elaborates the idea. You will most likely have an action creator for the purpose. A much better way will be that you have a LOGOUT_ACTION.
Once you dispatch this LOGOUT_ACTION. A custom middleware can then intercept this action, either with Redux-Saga or Redux-Thunk. Both ways however, you can dispatch another action 'RESET'. This way store logout and reset will happen synchronously and your store will ready for another user login.
Just a simplified answer to Dan Abramov's answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) =>
rootReducer(action.type === 'USER_LOGOUT' ? undefined : state, action);
Using Redux Toolkit and/or Typescript:
const appReducer = combineReducers({
/* your app’s top-level reducers */
});
const rootReducer = (
state: ReturnType<typeof appReducer>,
action: AnyAction
) => {
/* if you are using RTK, you can import your action and use it's type property instead of the literal definition of the action */
if (action.type === logout.type) {
return appReducer(undefined, { type: undefined });
}
return appReducer(state, action);
};
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage, IndexedDB, Web SQL, etc) and do a hard refresh of the page using window.location.reload(). It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix, I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if the upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with the ActionReducerMap method. At first, this new way of doing things might make resetting the state a challenge. It is actually straightforward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, let's say you want to reset the state from within app.module
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '#ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any>[] = [debug];
#NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
And that is basically one way to achieve the same affect with NGRX 4.
My workaround when working with typescript, built on top of Dan Abramov's answer (redux typings make it impossible to pass undefined to reducer as the first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx instead of original handleActions to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist.
When used with redux-persist, simply passing undefined state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState), but I couldn't stand it 'cuz I love metaprogramming.
Combining Dan Abramov's answer, Ryan Irilli's answer and Rob Moorman's answer, to account for keeping the router state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: [], message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: []}
default:
return state
}
};
I am not sure if this is optimal?
My take to keep Redux from referencing to the same variable of the initial state:
// write the default state as a function
const defaultOptionsState = () => ({
option1: '',
option2: 42,
});
const initialState = {
options: defaultOptionsState() // invoke it in your initial state
};
export default (state = initialState, action) => {
switch (action.type) {
case RESET_OPTIONS:
return {
...state,
options: defaultOptionsState() // invoke the default function to reset this part of the state
};
default:
return state;
}
};
I've created a component to give Redux the ability to reset state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is the same as what Dan Abramov said in their answer.
Github: https://github.com/wwayne/redux-reset
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State>[] = [ resetState ];
app.module.ts
import { StoreModule } from '#ngrx/store';
import { metaReducers, reducers } from './reducers';
#NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
Dan Abramov's answer helped me solve my case. However, I encountered a case where not the entire state had to be cleared. So I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Just an extension to #dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
For me to reset the state to its initial state, I wrote the following code:
const appReducers = (state, action) =>
combineReducers({ reducer1, reducer2, user })(
action.type === "LOGOUT" ? undefined : state,
action
);
I found that Dan Abramov's answer worked well for me, but it triggered the ESLint no-param-reassign error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
First on initiation of our application the reducer state is fresh and new with default InitialState.
We have to add an action that calls on APP inital load to persists default state.
While logging out of the application we can simple reAssign the default state and reducer will work just as new.
Main APP Container
componentDidMount() {
this.props.persistReducerState();
}
Main APP Reducer
const appReducer = combineReducers({
user: userStatusReducer,
analysis: analysisReducer,
incentives: incentivesReducer
});
let defaultState = null;
export default (state, action) => {
switch (action.type) {
case appActions.ON_APP_LOAD:
defaultState = defaultState || state;
break;
case userLoginActions.USER_LOGOUT:
state = defaultState;
return state;
default:
break;
}
return appReducer(state, action);
};
On Logout calling action for resetting state
function* logoutUser(action) {
try {
const response = yield call(UserLoginService.logout);
yield put(LoginActions.logoutSuccess());
} catch (error) {
toast.error(error.message, {
position: toast.POSITION.TOP_RIGHT
});
}
}
One thing Dan Abramov's answer doesn't do is clear the cache for parameterized selectors. If you have a selector like this:
export const selectCounter1 = (state: State) => state.counter1;
export const selectCounter2 = (state: State) => state.counter2;
export const selectTotal = createSelector(
selectCounter1,
selectCounter2,
(counter1, counter2) => counter1 + counter2
);
Then you would have to release them on logout like this:
selectTotal.release();
Otherwise, the memoized value for the last call of the selector and the values of the last parameters will still be in memory.
Code samples are from the ngrx docs.
A quick and easy option that worked for me was using redux-reset . Which was straightforward and also has some advanced options, for larger apps.
Setup in create store
import reduxReset from 'redux-reset'
// ...
const enHanceCreateStore = compose(
applyMiddleware(...),
reduxReset() // Will use 'RESET' as default action.type to trigger reset
)(createStore)
const store = enHanceCreateStore(reducers)
Dispatch your 'reset' in your logout function
store.dispatch({
type: 'RESET'
})
Approach with Redux Toolkit:
export const createRootReducer = (history: History) => {
const rootReducerFn = combineReducers({
auth: authReducer,
users: usersReducer,
...allOtherReducers,
router: connectRouter(history),
});
return (state: Parameters<typeof rootReducerFn>[0], action: Parameters<typeof rootReducerFn>[1]) =>
rootReducerFn(action.type === appActions.reset.type ? undefined : state, action);
};
why don't you just use return module.exports.default() ;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {} and you are ok because you don't want to encounter error when you check action.type inside the switch statement.
Another option is to:
store.dispatch({type: '##redux/INIT'})
'##redux/INIT' is the action type that redux dispatches automatically when you createStore, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
for me what worked the best is to set the initialState instead of state:
const reducer = createReducer(initialState,
on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
...initialState
})),
If you want to reset a single reducer
For example
const initialState = {
isLogged: false
}
//this will be your action
export const resetReducer = () => {
return {
type: "RESET"
}
}
export default (state = initialState, {
type,
payload
}) => {
switch (type) {
//your actions will come her
case "RESET":
return {
...initialState
}
}
}
//and from your frontend
dispatch(resetReducer())
Related
I have a redux store with 3 reducers:
let reducers = combineReducers({
config: configReducer,
data: dataReducer,
currentState: gameStateRecuder})
let store = createStore(reducers, applyMiddleware(thunkMiddleware));
In each of those reducers the initial store is empty, but once the App component mounts I use useEffect to replace each initial store inside a reducer with the one I receive with axios.get using redux-thunk. It looks like this in every reducer:
let initialState = [];
const SET_STATE = 'SET_STATE';
const configReducer = (state = initialState, action) => {
switch (action.type) {
case SET_STATE: {
return { ...action.state};
}
default:
return state;
}
const setState = (state) => ({ type: SET_STATE, state });
export const getConfigState = () => (dispatch) => {
getAPI.getConfig() //I import getAPI with all the REST API logic//
.then(response => {
dispatch(setState(response));
})
};
And the App trigger is:
const App = (props) => {
useEffect(() => {
props.getConfigState();
props.getDataState();
props.getGameState();
}, []);
return (
//JSX//
);
}
export default compose(connect(null, { getConfigState, getDataState, getGameState }))(App);
However, when the App mounts, I have this mess:
In the end, I get the state of each reducer replaced with the state of the one whose promise resolved the last one. I can try to wrap the app 2 more times with a HOC that does nothing but re-writes a state of the precise reducer, but I would still like to understand what causes a promise to affect other reducers besides the one he needs to effect.
A silly mistake, but maybe someone has the exact same problem - the solution is to give different case names for each reducer - SET_STATE need to become SET_GAME_STATE, SET_CONFIG_STATE, SET_DATA_STATE respectivly. I believe that's because of my misunderstanding on how the dispatch works.
I have an app where I want to implement authorization (registration, login, logout). I must use redux for that.
So far registration and login is working great, but I'm getting problems when I should delete data of the logged user when the user clicks the logout button.
I tried to put the login and logout cases in the same reducer, but when a user was logged I can't get access to the user's data, and instead of just take the old users data object and return the empty one it just adds an empty object to the user's data.
My redux state before login:
My redux state after login:
My redux state after logout
Here is my actions for login and logout:
export function userLoginSuccess(user) {
return {
type: 'USER_LOGIN_SUCCESS',
user
}
}
export function userLogout() {
return {
type: 'USER_LOGOUT'
}
}
Here is the reducer:
export function userLogin(state = {}, action) {
switch (action.type) {
case 'USER_LOGIN_SUCCESS':
localStorage.setItem('userToken', action.user.token);
return action.user;
case 'USER_LOGOUT':
localStorage.removeItem('userToken');
return {
...state,
userLogin: {}
}
default:
return state;
}
}
Here is the store initialization with combineReducers:
import { userLogin, companies, dataHaveError, dataIsLoading } from './redux/reducers';
const rootReducer = combineReducers({
companies,
userLogin,
dataHaveError,
dataIsLoading
})
const enhancer = applyMiddleware(thunk);
const store = createStore(rootReducer, {}, composeWithDevTools(enhancer));
I was trying to find a solution, but all that I find was without combineReducers and they were using initialState for solving this kind of problems, but in this case, how I understood, combineReducers is creating a state property for each reducer so I don't know how to handle this particular problem.
export function userLogin(state = {}, action) {
switch (action.type) {
case 'USER_LOGIN_SUCCESS':
localStorage.setItem('userToken', action.user.token);
return action.user;
case 'USER_LOGOUT':
localStorage.removeItem('userToken');
return {} // return empty state
default:
return state;
}
}
I'm new to Redux (and React as well) so this is probably a very elementar question, but I was unable to find a straight answer for it over the Internet.
There is a sign up screen on my app that I call SignUp. It is pretty straightforward and have just three inputs (email, password and passwordCheck) and one button (signup).
Thing is, I want to make my user life as simple as possible, so as passwordCheck is changed, I check it against password. If them match, signup is setted enabled and if them don't, signup goes disabled and a message is show to the user.
When I was using only React things were pretty simple - I simply made a this.state:
this.state: {
// ... stuff
password: "",
passwordIsValid: false, //test password against a predicate function
passwordMessage: "", //if the password is not valid there is a message
passwordStyle: "", //if password is wrong i put some classes here
passwordCheck: "",
passwordCheckMessage: "", //the 'passwords do not match' message goes here
passwordCheckStyle: "",
passwordsMatch: false
}
And then I handled the app's state inside SignUp.
Now I'm using Redux as well, so I killed this.state, moved everything to store and started using reducers instead of handlers.
Everything works for password, but passwordCheck is a different story. Since I need to know Store's password to check it against passwordCheck I have been unable (so far?) to do it on passwordCheckReducer. Instead, I removed passwordCheckMessage, passwordCheckStyle and passwordsMatch from passwordCheckReducer, calculating this values on SignUp. It seems to me as a very wrong and ugly way to settle the whole thing down though.
So, instead, I would like a more elegant and Redux-like solution.
If I could get store to be on passwordCheckReducer's state I would be able to set passwordsMatch and the others in the reducer while keeping it pure. Unfortunately, I have been unable to do it (so far?).
So, I would like to know if what I want to do is possible or if there's others, more desirables, ways to do it.
OBS1: Wherever I look on the Internet, I found the Redux official documentation on the subject of initializing state1. I do not think preloadedState is the way to resolve my problem, though, since it is used to iniatilize store, not to make it avaiable on my reducers. Instead, I simply need to have store - even when empty - visible to passwordCheckReducer.
OBS2: I know I could pass store as a key of action, but since the reducer pattern includes a state argument it seems redundant to me to define pass such in action.
Here is my Store:
// store.js
import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunkMiddleare from 'redux-thunk';
import { Reducers } from '../reducers/reducers';
const logger = createLogger();
const middleware = applyMiddleware(thunkMiddleare, logger);
export const Store = createStore(Reducers, middleware);
I'm using combineReducers:
// reducers.js
import { combineReducers } from 'redux';
import { emailReducer } from './emailReducer';
import { passwordReducer } from './passwordReducer';
import { passwordCheckReducer } from './passwordCheckReducer';
export const Reducers = combineReducers({
emailChange: emailReducer,
passwordChange: passwordReducer,
passwordCheckChange: passwordCheckReducer
});
And here is passwordCheckReducer:
// passwordCheckReducer.js
import { CHANGE_PASSWORDCHECK } from '../actions/actionTypes';
const initialState = {
passwordCheck: ""
};
export const passwordCheckReducer = (state=initialState, action) => {
const { payload, type } = action;
switch(type) {
case CHANGE_PASSWORDCHECK:
const passwordCheck = payload;
return {
...state,
passwordCheck
};
default:
return state;
}
};
Last, this is the implementation of mapDispatchToProps:
// SignUp.js
const mapDispatchToProps = dispatch => ({
handleEmailChange: e => dispatch(updateEmail(e.target.value)),
handlePasswordChange: e => dispatch(updatePassword(e.target.value)),
handlePasswordCheckChange: e => dispatch(updatePasswordCheck(e.target.value))
});
If I remember correctly, when you pass your reducer to combineReducers, that reducer will receive the redux module state (so, what the initialState was, not the entire app's root state object). You don't have access to state from other reducers.
You have a few options.
I think having separate reducers for password and passwordCheck is somewhat overkill. I would go with one reducer for the entire form:
const initialState = {
password: '',
passwordCheck: '',
// ....
}
export const signupReducer = (state=initialState, action) => {
const { payload, type } = action;
switch(type) {
case CHANGE_PASSWORD:
return { ...state, password: action.password}
case CHANGE_PASSWORDCHECK:
const passwordCheck = payload;
if (state.password != state.passwordCheck)
return { ...state, passwordCheck, error: "..."}; // or something like this
return {
...state,
passwordCheck
};
default:
return state;
}
};
If you want to split things up, you can always define reducers, and call them from a parent reducer, passing the whole parent-reducer state. Something like:
import passwordReducer from './passwordReducer'
import passwordCheckReducer form './passwordCheckReducer'
export const signupReducer(state = initialState, action) => {
state = passwordReducer(state, action)
state = passwordCheckReducer(state, action)
return state
}
If you are combining reducers, there is only one store object which stores all of the state from every reducer.
So you can access multiple reducers from one component like this:
const mapStateToProps = state => ({
password: state.passwordChange.password,
passwordCheck: state.passwordCheckChange.passwordCheck,
passwordsMatch: state.passwordCheckChange.passwordsMatch
})
export default connect(mapStateToProps, mapDispatchToProps)(SignUp)
Every time you update passwordCheck or password, your component's props will be updated.
So the best solution is actually to handle the passwordsMatch as a custom prop derived from the state of the two separate reducers. Something like:
const mapStateToProps = state => {
const passwordsMatch = state.passwordChange.password === state.passwordCheckChange.passwordCheck
return {
password: state.passwordChange.password,
passwordCheck: state.passwordCheckChange.passwordCheck,
passwordsMatch: passwordsMatch
}
}
My Redux Store is correctly being updated which can be seen using React Native Debugger. However, the props inside my component are not updating and are undefined.
In my component below you can see I have correctly mapped to the "sessionModerator" reducer. I have verified this and can see the prop when consoling this.props.
Component:
const mapStateToProps = state => {
return {
session: state.screenReducers.session,
list: state.screenReducers.sessionList,
sessionUser: state.screenReducers.sessionUser,
user: state.sharedReducers.user,
sessionListItem: state.screenReducers.sessionListItem,
sessionSortOrder: state.sharedReducers.sessionSortOrder,
sessionModerator: state.sharedReducers.sessionModerator
};
};
My reducer is added as seen below:
Reducers Index file:
import { reducer as sessionModerator } from './session/reducers/session-moderator';
export const reducers = combineReducers({
sessionModerator: sessionModerator,
});
Actions File:
import Types from '../../../types';
export const start = () => {
return {
type: Types.TYPES_SESSION_MODERATOR_START,
payload: true
};
};
export const stop = () => {
return {
type: Types.TYPES_SESSION_MODERATOR_STOP,
payload: false
};
};
Reducers File:
import Types from '../../../types';
export const reducer = (state = false, action) => {
switch (action.type) {
case Types.TYPES_SESSION_MODERATOR_START:
return action.payload;
case Types.TYPES_SESSION_MODERATOR_STOP:
return action.payload;
default:
return state;
}
};
In the below image you can see that the store is updated as the value for sessionModerator is set to "true", but the console of the actual props during the operation is undefined.
What I have tried:
I have tried various things mostly revolving around the structure of my state, for example, I tried adding the boolean inside an actual object and updating the value as an object property but that didn't seem to work. I feel like I am not updating the boolean correctly but haven't been able to figure it out.
Any help would be greatly appreciated. Thank you.
sessionModerator is in screenReducers in the debugger not in sharedReducers as in your mapStateToProps.
Try this one:
const mapStateToProps = state => {
return {
session: state.screenReducers.session,
list: state.screenReducers.sessionList,
sessionUser: state.screenReducers.sessionUser,
user: state.sharedReducers.user,
sessionListItem: state.screenReducers.sessionListItem,
sessionSortOrder: state.sharedReducers.sessionSortOrder,
sessionModerator: state.screenReducers.sessionModerator
};
};
Is there a way to structure const reducer = (state = initialState, action) in such a manner that the method isn't bloated by a bunch of switch cases?
My idea was to put related actions in arrays and check them with Array.prototype.includes() when handling an action.
I would then extract the switch cases that correlate to specific actions in new methods (for example the List component would have LIST_ADD, LIST_REMOVE etc.) and call those methods instead of just running through 100 cases in the const reducer = (state = initialState, action)method.
That would tax performance but it would be at least structured.
Any better ideas?
The offical Redux docs provide this very handy reducer creator:
function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
which lets you create your reducer as follows:
const reducer = createReducer(initialState, {
[actionType.ACTION1]: specificActionReducer1,
[actionType.ACTION2]: specificActionReducer2,
}
No switch statements!
I use a library called reduxsauce which removes the need for large switch statements.
https://github.com/infinitered/reduxsauce
Instead it binds actions to methods with this syntax:
export const INITIAL_STATE = {
values: {},
}
export const reducerFunction = (state, action) => {
const values = action.value;
return {
...state,
values,
};
};
// map the action types to the reducer functions
export const HANDLERS = {
[Type.ACTION_NAME]: reducerFunction,
...
}
// call createReducer to magically tie it all together
export default createReducer(INITIAL_STATE, HANDLERS);
You could try redux-named-reducers for this as well. Allows you to compose reducers like so:
moduleA.reduce(SOME_ACTION, action => ({ state1: action.payload }))
moduleA.reduce(SOME_OTHER_ACTION, { state2: "constant" })
It has the added benefit of being able to access the reducer state anywhere, like in mapDispatchToProps for example:
const mapDispatchToProps = dispatch => {
return {
onClick: () => {
dispatch(someAction(getState(moduleA.state1)));
}
};
};