Search code examples
reactjsreduxredux-thunkredux-middleware

dispatch is not defined on my functions using react and redux


I am trying to use react-redux-loading-bar to show a loading bar during fetching data from API servers, I don't use promise middleware so I decided to use it without, the example says do this

import { showLoading, hideLoading } from 'react-redux-loading-bar'

dispatch(showLoading())
// do long running stuff
dispatch(hideLoading())

And it gives me this.

Uncaught ReferenceError: dispatch is not defined

I had similar issues with other libraries and gave up that time, this time I want to actually understand how this works, so any info is greatly appreciated. Heres the code that causing the error, speicifc function and class names stripped.

import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import { showLoading, hideLoading } from 'react-redux-loading-bar'


import * as xxxxxActions from '../../actions/xxxxx'


class xxxxxx extends React.Component {

    constructor(props) {
        super(props)

        this.handleclick = this.handleclick.bind(this)
    }

    handleclick(){
        dispatch(showLoading())
        asynchronousGetFunction( target_url, function (data) {
            dispatch(hideLoading())
        })
    }

    render() {

        return  <li onClick={this.handleclick}>yyyyyyy</li>
    }
}

function mapStateToProps( state ){
    return {
    }
}

function mapDispatchToProps(dispatch, state) {

    return {
        xxxxxActions: bindActionCreators( xxxxxActions, dispatch )
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(xxxxxx)

Solution

  • You need to pass dispatch function to your props:

    function mapDispatchToProps(dispatch, state) {
        return { 
            xxxxxActions: ....,
            showLoading: function () {
                dispatch(showLoading());
            },
            hideLoading: function () {
                dispatch(hideLoading());
            },
        };
    }
    

    Then, use it in your component:

    this.props.showLoading();
    ...
    this.props.hideLoading();