Search code examples
javascriptreact-nativereduxexporedux-thunk

Redux - dispatch is undefined in action


I'm new to redux, but i have a problem that i don't understand and it can not fix it.

The problem is, when i want to dispatch inside my action, I've got an error who said :

dispatch is not a function

Yep, he is undefined and this is the point, why he is undefined ?

export const clearError = dispatch => {
    console.log('clear error')
    console.log(dispatch)

    dispatch({
        type: 'CLEAR_ERROR'
    })
}

I call the clearError action from Main.js, maybe my initialization is not correct, but i've tried several way, like bindActionCreators...

Main.js (how i pass props and dispatch with connect)

const mapStateToProps = (state) => state
const mapDispatchToProps = {
    clearError: clearError
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Main)

I'm really confused because in other component I use two others actions made by the same way and everything it's ok...

I don't know if it can help you to understand the origin of the problem but i show you how i configure the store to call configureStore() in App.js.

import {applyMiddleware, createStore} from "redux";
import thunk from 'redux-thunk';

import reducers from './reducers'

const configureStore = () => {
    const middleware = [thunk]
    return createStore(reducers, applyMiddleware(...middleware))
}

export default configureStore

I'm listening every help and advices about redux and the best way to use it !

Really thanks to you for reading ❤️


Solution

  • The issue is that you are not returning a function from your action creator with dispatch as one of the arguments:

    export const clearError = () => dispatch => {
    

    Under the hood, when you pass your action creators to mapDispatchToProps, Redux "maps" that dispatch argument to your action creators, and then assigns the mapped action creators to Component properties.
    This is also why you have to call this.props.clearError() instead of just clearError().