Mr. Duc Nguyen
Mr. Duc Nguyen

Reputation: 1069

Redux won't update React component when state change

I'm trying to get my simple Redux React test work. I'm really new to both Redux and React. I've been reading through Redux documentation and in Troubleshooting section, it said that reducer should return new object everytime. In my case, I think I'm returning new object...

Any suggestions are appreciate!

My reducer:

const memberOpReducer = (state = {isLoading: true, isLoggedIn: false}, action) => {
  switch(action.type) {
    case 'CHECK_LOGIN_STATUS':
      return {
        isLoading: true
      }
    case 'LOGIN_STATUS':
      return {
        isLoading: false,
        isLoggedIn: action.response.status === 'connected',
        response: action.response
      };
    default:
      return state;
  }
};

My actions:

const checkLoginStatus = () => ({
  type: 'CHECK_LOGIN_STATUS'
});

const loginStatus = response => ({
  type: 'LOGIN_STATUS',
  response: response
});

const getLoginStatus = (options = {}) => dispatch => {
  dispatch(checkLoginStatus());
  FB.getLoginStatus(function (response) {
    dispatch(loginStatus(response));
  }, options);
}

Please have a look at this working pen: https://codepen.io/mrducnguyen/pen/rGxpGR

Upvotes: 0

Views: 51

Answers (1)

Sidney
Sidney

Reputation: 4775

The problem is in your mapStateToProps function:

// Your function, just for reference
const mapStateToProps = state => {
  return {
    isLoggedIn: state.isLoggedIn === undefined ? false : state.isLoggedIn,
    isLoading: state.isLoading === undefined ? true : state.isLoading,
    response: state.response
  }
}

You're accessing state.isLoggedIn, but you should be accessing state.memberOpReducer.isLoggedIn, because you used combineReducers which namespaces all of the fields of that reducer under the reducer's name. Same for all the other fields, of course.

// Fixed version
const mapStateToProps = state => {
  return {
    isLoggedIn: state.memberOpReducer.isLoggedIn,
    isLoading: state.memberOpReducer.isLoading,
    response: state.memberOpReducer.response
  }
}

Upvotes: 1

Related Questions