2
votes

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?

2
Please share your reducer here - Sakhi Mansoor
because You are dispatching in componentDidMount which this method gets called only once per component - Hemadri Dasari
No it’s not an issue with componentDidMount(). It won’t be mounted again unless it is unmounted before - Sakhi Mansoor

2 Answers

0
votes

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

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.