Search code examples
reactjsreact-reduxredux-thunk

Where should I put my dispatch in lifecycle react redux


Im having troubles with my app, I want to retrieve an array Lessons from User collection, based on user id logged in. Im using redux thunk, jwt auth

I tried to dispatch my getMyLessons in componentDidMount but it takes this.props.auth.user as null param, but if I used it on render() it loads (it gets freezed but loaded it lol), so I think it's a lyfecicle issue

class DashboardSidebar extends Component {
    componentDidMount(){
        this.props.getMyLessons(this.props.auth.user._id);
    }     

    static propTypes = {
        auth: PropTypes.object.isRequired,
        lesson: PropTypes.object.isRequired,
        getMyLessons: PropTypes.func.isRequired
    }

const mapStateToProps = (state) => ({    
    auth: state.auth,
    lesson: state.lesson
});

export default connect(mapStateToProps,{ getMyLessons })(DashboardSidebar);

Solution

  • You can do it in componentDidUpdate:

    componentDidUpdate(prevProps) {
      const {user} = this.props.auth;
      if (user && user._id && user._id !== prevProps.auth.user._id) {
        this.props.getMyLessons(user._id);
      }
    }