3
votes

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;
4
where you dispatching it ? - Dhaval Patel
Please share mapStateToProps function - Umair Farooq
in my Login.js file, please check check 'mapDispatchToProps' - IDF
Please also share mapStateToProps, mapDispatchToProps is on adding function. - Umair Farooq
@VladimirBogomolov added codesandbox.io/s/148rm8qy9q - IDF

4 Answers

1
votes

-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
    };
};
0
votes

Think there might be a problem with your mapStateToProps. Try accessing your isLoggedIn state like :

const mapStateToProps = state => {
    return {isLoggedIn : state.isLoggedIn};};
-1
votes

use componentwillupdate() to controllr when to update return false to not update

-1
votes

You should be calling dispatch differently:

const mapDispatchToProps = (dispatch, val) => {
  return {
    setLoggedIn : (val) => dispatch({ type: 'SET_LOGGED_IN', value: val }),
  }
};

Try that and it should work for you.