Reputation: 467
I'm new to react-redux and I'm using the react-thunk middleware. I'm getting the error "Uncaught TypeError: dispatch is not a function" whenever I try to run my action creator (by pressing my button). Anyone know what's going on?
src/actions/index.js
function editUserName (newUserName) {
return {
type: 'CHANGE_USER_NAME',
newUserName: newUserName
}
}
export function editUserNameDelegate () {
return function (dispatch, getState) {
return dispatch(editUserName("thunkUser"))
}
}
src/containers/admin.js
import { editUserNameDelegate } from '../actions/index'
...
<input type="button" onClick={ editUserNameDelegate() } value="edit UserName" />
Upvotes: 3
Views: 13184
Reputation: 55
If This Error Is As A Result Of Using context you might consider importing it as: const {state, dispatch} = useContext(location of the context)
Upvotes: 0
Reputation: 1566
You should provide what is src/containers/admin.js function or class?
If it is function component you should use onClick={() => editUserNameDelegate()}
Upvotes: 0
Reputation: 67577
You're executing the editUserNameDelegate
function inside of render
, instead of passing it as the onClick
handler. You want onClick={editUserNameDelegate}
instead.
Also, if you're writing it that way, you need to make sure that the function is bound up to dispatch when you call it. You can do that like:
export default connect(null, {editUserNameDelegate})(MyComponent)
And then pass onClick={this.props.editUserNameDelegate}
in your render function.
Upvotes: 6
Reputation: 3463
The store is what provides the dispatch
function. So you either need to connect your component to the store using something like connect
from react-redux (https://github.com/reactjs/react-redux), or you need to call store.dispatch(editUserNameDelegate())
.
You also need to make sure you have added redux-thunk as middleware in your store. See more about redux-thunk here: https://github.com/gaearon/redux-thunk
Upvotes: 0