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.