Search code examples
javascriptreactjsreduxreact-reduxredux-form

reducer does not update state in react redux


I am trying update state using react-redux but the state is not being updated. new value is coming to "if (action.type === 'SET_LOGGED_IN')" in reducer, but not updating the isLoggedIn as true. What was wrong? find the code

Login.js

function handleLoginClick(username, password, e) {
    e.preventDefault();

    post('/createUser', { username, password })
        .then(({ status }) => {
            if (status === 200) {
                console.log(this.props);
                this.props.setLoggedIn(true);
                this.props.history.push('/');
            }else{
                this.props.setLoggedIn(false);

            }
        })
        .catch(error => {
        .........
        })
}
..................
const mapStateToProps = state => {
    return {isLoggedIn : state.reducer.isLoggedIn};};
const mapDispatchToProps = dispatch => {
    return {setLoggedIn : (value) => dispatch({type: 'SET_LOGGED_IN', value: value}),}};

export default compose(
    withStyles(styles),
    withRouter,
    connect(mapStateToProps, mapDispatchToProps)
)(NewLogin);

reducer.js

import { combineReducers } from 'redux';
import { reducer as reduxFormReducer } from 'redux-form';

const initialStates = {
    isLoggedIn : false
};

const reducers = combineReducers({
    reducer : (state = initialStates, action) => {
        //console.log(action);
        if (action.type === 'SET_LOGGED_IN') {
            //console.log(action);
            return {
                ...state,
                isLoggedIn: action.value
            };
        }
        return state;
    },

        form: reduxFormReducer, // mounted under "form"
});

export default reducers;

Solution

  • -Fixed the error-

    In my code, state is updated correctly. When I accessing, I had used state.isLoggedIn which is undefined. I replaced it from state.reducer.isLoggedIn. Now everything works charm.

    Thank you @UmairFarooq , @VladimirBogomolov and all who commented and gave a try to fix it.

    const mapStateToProps = state => {
        return {
          isLoggedIn : state.reducer.isLoggedIn
        };
    };