2

this.props.authState stays the same although I'm dispatching an action in my componentDidMount function:

componentDidMount() {
      if (localStorage.getItem('token')) {
        dispatch(updateAuthState('AUTHENTICATED'));
      }
  }

render() {
 <div>{this.props.authState}</div>
}

Home.propTypes = {
    authState: PropTypes.string
};

const mapStateToProps = (state) => {
    return {
        authState: state.authState
    }
};

const mapDispatchToProps = (dispatch) => {
  return {

  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

the output is NO_AUTH (the initial value of authState)

Reducer:

export function authState(state = "NO_AUTH", action) {
    switch (action.type) {
        case 'AUTH_STATE':
            return action.authState;
        default:
            return state;
    }
}

any idea why?

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

2 Answers2

0

If you’re mutating the state then component will not be re rendered. You need to return {...state, authState} from your reducer. And you verify your updated state in

componentWillReceiveProps(nextProps)
  {
   }

I hope this would solve the issue.

Sakhi Mansoor
  • 7,832
  • 5
  • 22
  • 37
  • 1
    You only use `cwrp` if you have internal component state that you need to sync with props dynamically. Otherwise you don't need `cwrp` as `mapStateToProps` is going to assign new props thus trigger component rerender with all update lifecycles. – Karen Grigoryan Aug 26 '18 at 08:21
  • I just stated it to verify the state changes, didn’t recommend to use it. – Sakhi Mansoor Aug 26 '18 at 08:23
0

You're currently dispatching directly inside the componentDidMount which isn't mapped into:

connect(mapStateToProps, mapDispatchToProps)(Home);

This should do the job:

componentDidMount() {
      if (localStorage.getItem('token')) {
        this.props.onUpdateAuthState('AUTHENTICATED');
      }
  }

const mapDispatchToProps = (dispatch) => {
  return {
    onUpdateAuthState: function(authState) {
      dispatch(updateAuthState(authState));
    }
  }
};

Now, this will get the authState:

const mapStateToProps = (state) => {
    return {
        authState: state.authState
    }
};
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231