Fabrice
Fabrice

Reputation: 475

How to bind redux dispatch method to a "dumb" component

I have a Logout component that just renders a button that should dispatch a logout action to the reducer. How can I bind the dispatch method to that component without using redux connect(...)? or is the best way to use connect() even if it's a dumb component like this one?

my component looks like this and I make the dispatch method available by importing the store but it doesn't feel right:

import React from "react";
import { userActions } from '../_actions';
import { store } from '../_helpers/store.js';

const LogoutButton = ({ history }) => (
    <button
        type="button"
        className="logout"
        onClick={() => {
            store.dispatch(userActions.logout());
            history.push(`${process.env.PUBLIC_URL}/signin`);
        }
    }>
    Logout
    </button>
);

export default LogoutButton;

Upvotes: 0

Views: 447

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281686

connect should be the way to go whether its a Functional component or a conventional React component. The other advantage that you get with connect is that it is a PureComponent and hence takes care of updates

const LogoutButton = ({ history }) => (
    <button
        type="button"
        className="logout"
        onClick={() => {
            userActions.logout();
            history.push(`${process.env.PUBLIC_URL}/signin`);
        }
    }>
    Logout
    </button>
);

export default connect(null, userActions)(LogoutButton);

Upvotes: 1

Kuldeep Saxena
Kuldeep Saxena

Reputation: 2003

A dumb component should be driven by props, So you can just pass a function as a prop in your LoginButton component form your container component.

Example:

Parent:

<LoginButton onPress={store.dispatch(userActions.logout())}/>

Child:

const LogoutButton = ({ history, onPress }) => (
 <button
    type="button"
    className="logout"
    onClick={() => {
        onPress();
        history.push(`${process.env.PUBLIC_URL}/signin`);
    }
 }>
 Logout
 </button>
);

Upvotes: 1

Krasimir
Krasimir

Reputation: 13529

It doesn't feel right yes. You'd better use the convenient way with connect. Have in mind that relying on the module system to deliver dispatch or data from the store will potentially make your testing difficult. If you use connect those stuff will come from React's context and you can easily mock them up.

Upvotes: 1

Related Questions