1

How do I properly dispatch actions in React Lifecycle Methods?

Hello, friends I have an action called checkSession() inside my very parent component (App.jsx). This action helps me to get user info.
This is how App.jsx looks like:

class App extends Component {
  componentWillMount() {
    this.props.checkSession();
  }
  render() {
    if (this.props.auth === null) {
      return <div>Loading...</div>;
    } else {
       return (
         <BrowserRouter>
           <Route path="/cart" component={Cart} />
         </BrowserRouter>
      );
    }
  }
}
const mapStateToProps = ({ auth }) => { auth };
export default connect(mapStateToProps, { checkSession })(App);

How do I properly dispatch another action inside the Cart.jsx component. I try to dispatch the action inside the componentWillReceiveProps methods but it creates an infinite loop. My Cart.jsx component looks like this:

import { getCart } from "../../actions"; 

class Cart extends Component {
  componentWillReceiveProps(nextProps, nextState) {
    if (nextProps.auth) {
      this.props.getCart(nextProps.auth.googleId);
    } else {
      this.props.getCart(null);
    }
  }
  render() {
    ......some staff  
  }
}
const mapStateToProps = ({ auth }) => { auth };
export default connect(mapStateToProps, { getCart })(Cart);

I have just tried to dispatch this action inside the ComponentWillMount - but my props are not ready yet so I got an error. Help me please with any advice, and sorry for my English.

Joshua
  • 3,055
  • 3
  • 22
  • 37
jsDev
  • 136
  • 2
  • 12

1 Answers1

2

Maybe you have to detect if the props have changed before firing the dispatch:

componentWillReceiveProps(nextProps, nextState) {
    const currentId = this.props.auth && this.props.auth.googleId;
    const nextId = nextProps.auth && nextProps.auth.googleId;
    if (currentId !== nextId) {
        this.props.getCart(nextProps.auth.googleId);
    }
}
Faly
  • 13,291
  • 2
  • 19
  • 37
  • Thank you, it working, but when I refresh page this action ` this.props.getCart(nextProps.auth.googleId)` won't be executed. And I can't use `componentWillMount` because of infinite loop. How can i deal with this? – jsDev Mar 23 '18 at 09:48