Categories
React Answers

How to fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux?

Spread the love

Sometimes, we want to fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux.

In this article, we’ll look at how to fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux.

How to fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux?

To fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux, we call the connect function with the component to make the dispatch prop available within the component.

For instance, we write

import { connect } from "react-redux";

//...

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id));
    },
  };
};

const VisibleTodoList = connect(mapStateToProps, mapDispatchToProps)(TodoList);

to add the mapStateToProps and mapDispatchToProps functions to make the Redux state and the dispatch function available to components respectively.

And then we call connect with both functions to return another function.

We then call the returned function with TodoList and assign the returned component to VisibleTodoList to make dispatch available in VisibleTodoList as a prop.

Conclusion

To fix ‘dispatch’ is not a function when argument to mapToDispatchToProps() error in React and Redux, we call the connect function with the component to make the dispatch prop available within the component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *