Reputation: 1008
AuthReducer-reducer file
const initialState = {
isAuthenticated: false,
}
const authReducer = (state = initialState, action: any) => {
switch (action.type) {
case 'SIGN_IN':
state = {
...state,
isAuthenticated: true,
}
break;
case 'SIGN_OUT':
state = {
...state,
isAuthenticated: false,
}
break;
default:
state = {
isAuthenticated: false,
}
}
return state;
}
export default authReducer;
dispatcher-dispatching action
const authDispatch = useDispatch();
authDispatch({ type: 'SIGN_IN'});
Store
const rootReducer = combineReducers({
user: AuthReducer
}); const store = createStore( rootReducer, compose(applyMiddleware(thunk)) );
Result
{isAuthenticated: false}
Result i want
{isAuthenticated: true}
How can I solve this error I am unable to solve this error, please help me...
Upvotes: 0
Views: 467
Reputation: 44078
Your default
case is setting isAuthenticated: false
- and that default
case will be hit by every Redux action ever dispatched that is not "SIGN_IN"
or "SIGN_OUT"
. So once one other action is dispatched, it returns to isAuthenticated: false
.
You should have
default:
return state
Also, please note that you are generally writing a very old style of Redux that we do not recommend any more as it requires tons of boilerplate (and this would also not not have happened with modern Redux). You might be following a very outdated tutorial. For an up-to-date tutorial, please see the official Redux tutorial
Upvotes: 0
Reputation: 537
Reading from your comments I can make that you need to preserve redux data on refresh. Redux values won't be persisted on refresh it is how redux is,If you intent to preserve values on refresh you need to persist Redux state.
This can be achieved through a npm package "redux-persist". You can follow this link,documentation is quite descriptive
https://www.npmjs.com/package/redux-persist
Upvotes: 0
Reputation: 15319
I think it should be.you are returning state incorrectly .
switch (action.type) {
case 'SIGN_IN':
return {
...state,
isAuthenticated: true,
}
case 'SIGN_OUT':
return {
...state,
isAuthenticated: false,
}
default:
return {
...state,
isAuthenticated: false,
}
}
Upvotes: 0