dispatch is not defined on my functions using react and redux

6k views Asked by At

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)
3

There are 3 answers

3
Daniel Tran On BEST ANSWER

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();
0
Hemerson Carlin On

Once you connect your component, dispatch becomes a prop. The same applies for xxxxxActions...

In that case, the handle would be:

handleclick(){
  this.props.dispatch(...)
}
1
Gothic Prince On

You don't need use "dispatch" in components. Bind your functions with dispatch in mapDispatchToProps.

Read more about mapDispatchToProps.