Search code examples
reactjsdispatch

this.props.dispatch is not a function in react js component file


In pagination 'onSelect' event I am calling an function that is define outside of render and in component's class. But when event firing below error coming -

BlogList.js:101 Uncaught TypeError: this.props.dispatch is not a function

here is my code snippit -

import React from 'react'; 
import StaticLayout from '../Layout/StaticLayout';
import { Link } from 'react-router-dom';
import { getBlogList } from '../actions/signupActions';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux'; 
import dateFormat from 'dateformat';

import { Pagination } from 'react-bootstrap'; 
import { push } from 'react-router-redux'; 
import queryString from 'query-string'


class BlogList extends React.Component {
    constructor(props){
        super(props);
        document.title = "Blogs";

        this.changePage = this.changePage.bind(this);
    }

    componentDidMount() {
        this.props.getBlogList();
    }

    render(){

        //===pagination variable========
        const per_page = 1;
        let pages = 0;
        if(this.props.blogListData !== undefined){
            pages = Math.ceil(this.props.blogListData.count / per_page) ;
        } 
        const current_page = this.props.page;
        const start_offset = (current_page - 1) * per_page;
        let start_count = 0;
        //===End pagination variable========


        return(
            <StaticLayout>
                <blog list related html />
                <Pagination className="users-pagination pull-right" bsSize="medium" maxButtons={10} first last next prev boundaryLinks items={pages} activePage={current_page} onSelect={this.changePage} />
            </StaticLayout>
        );  
    }

    changePage(page){
        alert(page);
        this.props.dispatch(push('/?page_no='+page))
    }


}


function mapStateToProps(state,ownProps){
    var queryParam = queryString.parse(ownProps.location.search);
    return { 
        blogListData: state.UserReducer.blogData,
        page: Number(queryParam.page_no) || 1,
    }
}

function mapDispatchToProps(dispatch) {
      return bindActionCreators({getBlogList: getBlogList}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps) (BlogList);

Plz let me know what i am doing wrong ?


Solution

  • dispatch is available to the component when you use connect only if you are not overriding it with the a custom function. which in your case is a mapDispatchToProps function. So what you can do is make the push action available as a prop to the component by adding it to the mapDispatchToProps function like

    function mapDispatchToProps(dispatch) {
      return bindActionCreators({getBlogList: getBlogList, push: push}, dispatch)
    }
    

    and use it like

    changePage(page){
        alert(page);
        this.props.push('/?page_no='+page)
    }