why my redux state not updating
13,602
You are not updating the payload data in your reducer
export default (state = initialState, action) => {
switch(action.type){
case SET_CURRENT_USER:
return {...state, user: action.payload} //update user here
}
...
default: return state;
}
}
the above code uses es6 features and the assumption made is isAuthenticated
and error
are part of the initial state.
You are just returning the same JSON which is why your state is not updating.
Author by
PrudhviD
Updated on July 22, 2022Comments
-
PrudhviD almost 2 years
state not updating.when action is dispatched the state should update to isAuthenticated to true..but the state not updating..redux returning the initial state not the updated state.
export function setCurrentUser(user) { console.log(user); return { type: "SET_CURRENT_USER", user }; } ... export function login(userData) { return dispatch => { return axios.post('/user/auth',userData).then((res) => { const { status, sessionId, username, error} = res.data; if(status === "success"){ dispatch(setCurrentUser(sessionId)); }else { dispatch(invalidUser(error)); } }); } } //reducers import { SET_CURRENT_USER, INVALID_USER } from "../actions/types"; import isEmpty from "lodash/isEmpty"; const initialState = { isAuthenticated : false, user: {}, error:{} }; export default (state = initialState, action) => { switch(action.type){ case SET_CURRENT_USER: return { ...state, isAuthenticated: !isEmpty(action.user), user:action.user } ... default: return state; } }
//component
onSubmit(e){ e.preventDefault(); this.setState({ errors: {}, isLoading:true }); this.props.login(this.state).then( (res) => { console.log(this.props.userData); if(this.props.userData.isAuthenticated) this.context.router.push("greet"); },
(err) => this.setState({ errors: err.response.data, isLoading: false }) );
}
.....
function mapStateToProps(state) { return { userData: state.authReducers }; } export default connect(mapStateToProps, { login })(LoginForm);
-
PrudhviD over 7 yearsreturn { 14 | ...state, > 15 | {user:action.user} | ^ 16 | 17 | } syntax error
-
StateLess over 7 yearscan you elaborate ?
-
PrudhviD over 7 yearsi tried to excute your code..but getting syntax error
-
StateLess over 7 yearswhere? which line? are you using es6, babel?
-
PrudhviD over 7 yearsreturn {...state, >{user: action.payload}} //yes am using es6 babel
-
StateLess over 7 yearshey what is > doing there
-
StateLess over 7 yearsSmall typo in there, check now
-
StateLess over 7 yearsconsole some value in switch case of SET_CURRENT_USER and check if you can see that
-
PrudhviD over 7 yearsconsole not returning
-
StateLess over 7 yearsIf you are not seeing console then it seems reducers are not invocating.try debugging to find why it is happening
-
PrudhviD over 7 yearsits working now changed case set_current_user to case "set_current_user" but i have a doubt why the first case didnt work ..i have imported the types too