Jacek Wojcik
Jacek Wojcik

Reputation: 1253

Redux connect does not pass `dispatch` to connected component

please have a look at my code:

const Checkout = ({items, setItemAmount}: CheckoutDisplayProps, dispatch: AppDispatch) => {
    useEffect(() => {
        dispatch(getOrders());
    }, [dispatch]);

    return <CheckoutDisplay items={items} setItemAmount={setItemAmount} />;
};

const mapStateToProps = (state: State) => {
  return {
    items: state.checkout.items,
  };
};

const mapDispatchToProps = (dispatch: AppDispatch) => {
  return {
    setItemAmount: (id: number, amount: number) =>
    dispatch(setItemAmount(id, amount)),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Checkout);

what I am trying to achieve is to dispatch action in useEffect hook, I expect to have dispatch passed to Checkout component by connect.

It turns out that dispatch is not being passed as a function, it is just an empty object. Why?

Thank you!

Upvotes: 0

Views: 297

Answers (2)

markerikson
markerikson

Reputation: 67439

Correct. When you supply a value for mapDispatch, you no longer get props.dispatch automatically. It's up to you to include it as a prop if desired, but most of the time you don't need it because you're just calling bound action creators inside the component.

See the React-Redux usage guide for mapDispatch and the Redux FAQ entry on "why don't I have props.dispatch?" for more details.

Upvotes: 2

Paul
Paul

Reputation: 1022

If you're using hooks, just use useDispatch, and useSelector.

import { useDispatch, useSelector } from 'react-redux';

const Checkout = () => {
  const dispatch = useDispatch();
  const items = useSelector(state => state.checkout.items);

  const setItemAmountCallback = (id: number, amount: number) => {
    dispatch(setItemAmount(id, amount));
  };

  useEffect(() => {
    dispatch(getOrders());
  }, []);

  return <CheckoutDisplay items={items} setItemAmount={setItemAmountCallback} />;
};

Upvotes: 1

Related Questions