Boris Grunwald
Boris Grunwald

Reputation: 2712

Redux-thunk "dispatch is not a function"

I have configured redux-thunk the following way

import {BrowserRouter} from "react-router-dom";
import {createStore, applyMiddleware, compose} from "redux";
import Provider from "react-redux/es/components/Provider";
import braintrainer from "./store/reducers/braintrainer";
import thunk from 'redux-thunk';



const store = createStore(
    braintrainer,
    applyMiddleware(thunk),
); 



ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <BrainTrainer/>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));

Then in one of my components I map the function onLoginClicked to dispatch the startLogin action

const mapDispatchToProps = dispatch => ({
    onDifficultySelected: difficulty => dispatch({ difficulty, type: 'SET_DIFFICULTY' }),
    onLoginClicked : (username,password) => dispatch(() => startLogin(username,password))
});
export default withRouter(connect(null, mapDispatchToProps)(BrainTrainer));

I pass the onLoginClicked function down to my Login component and call it when the login button is clicked

<button type='button' className='login-btn' onClick={onLoginClicked(passWord,userName)}>
    {isLogin ? 'Login' : 'Sign up'}
</button>

My startLogin action creator looks like this

import axios from 'axios';

const baseUrl = 'http://localhost:5000';

export const login = (token) => ({
    type: 'LOGIN',
    token
});


export const startLogin = (password,username) => {
    return dispatch => {
        axios.post(baseUrl+'/api/auth/login',{
            username,
            password
        }).then((data) => dispatch(login(data.data.token)))
    }
};

Yet when I invoke the onLoginClicked function I get this error in my startLogin action creator.

Unhandled Rejection (TypeError): dispatch is not a function

Can anyone tell me where I went wrong?

Picture of the error

enter image description here

Upvotes: 0

Views: 432

Answers (1)

Aprillion
Aprillion

Reputation: 22304

In dispatch(fn), the fn needs to be a "thunk" function - to accept dispatch itself as the first argument. Not an anonymous function:

dispatch(() => startLogin(username,password))

But the return value from startLogin:

dispatch(startLogin(username,password))

Upvotes: 2

Related Questions