title: React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component
body: <p>I'm having problems with this. I'm creating a small app with react redux.</p>
  
  <p>In the code below is my app.js component. It was working fine until I tried to use the mapDispatchToProps function inside connect. The problem is that I cannot invoke the dispatch action on componentDidMount anymore. The actions that were in componentDidMount and that now are on mapStateToProps need to be called on comoponentDidMount. Any clues in how to do that?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>import React, { Component } from 'react';
  import './App.css';
  import '../../node_modules/bootstrap/less/bootstrap.less';
  import { Route } from 'react-router-dom'
  import * as ReadableAPI from '../ReadableAPI'
  import HeaderNavigation from './HeaderNavigation';
  import TableBody from './TableBody';
  import { connect } from 'react-redux';
  import sortAsc from 'sort-asc';
  import sortDesc from 'sort-desc';
  import {
    selectedCategory,
    fetchCategoriesIfNeeded,
    fetchPostsIfNeeded,
    invalidateSubreddit,
    orderPost
  } from '../actions'
  
  class App extends Component {
  
    state = {
     posts: []
    }
  
    componentDidMount() {
     const { dispatch, selectedCategory, fetchCategories, fetchPosts} = this.props
        //dispatch(fetchCategoriesIfNeeded(selectedCategory))
        //dispatch(fetchPostsIfNeeded(selectedCategory))
    }
  
    orderByScoreAsc = (posts) =&gt; {
  
         return posts.sort(sortAsc('voteScore'))
  
       }
  
      orderByScoreDesc = (posts) =&gt; {
  
         return posts.sort(sortDesc('voteScore'))
  
       }
  
      render() {
  
      const { navCategories, posts } = this.props
  
       return (
         &lt;div&gt;
           &lt;HeaderNavigation navCategories = {navCategories} /&gt;
  
           &lt;Route exact path="/" render={()=&gt;(
             &lt;TableBody 
              showingPosts={posts} 
             /&gt;)}
           /&gt;
  
           
           
         &lt;/div&gt;
       );
     }
  }
  
  function mapStateToProps ( state ) {
    const { categories, posts } = state
    return {
       navCategories: categories.items,
       posts: posts.items
    }
  }
  
  function mapDispatchToProps (dispatch) {
    return {
      changeOrder: (data) =&gt; dispatch(orderPost(data)),
      fetchCategories: (data) =&gt; dispatch(fetchCategoriesIfNeeded(data)),
      fetchPosts: (data) =&gt; dispatch(fetchPostsIfNeeded(data))
    }
  }
  
  
  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(App)</code></pre>
  </div>
  </div>
  </p>