0

Is something like this bad practice?

SendInfoButton.js

import React from 'react';
import { sendInfo } from '../actions/index';

export const SendInfoButton = ({currentUser}) => (
    <div>
        <button onClick={() => sendInfo(currentUser)} />
    </div>
)

actions/index.js

import { store } from '../reducers/index';
import { SEND_INFO } from '../constants/index;

export const sendInfo = (currentUser) => store.dispatch({type: SEND_INFO, payload: currentUser})

It seems more efficient to import actions directly into the components this way, as opposed to using mapDispatchToProps and passing down actions to components that won't use them. I'm also more inclined to import actions like this because I already have components with a large number of props and would rather not add to that.

Sir Sudo
  • 31
  • 1
  • 5
  • 1
    Relevant : https://stackoverflow.com/questions/39419237/what-is-mapdispatchtoprops – charlietfl Sep 13 '18 at 03:54
  • 1
    Yes, this can be considered bad practice, you're hardcoding the app to use specific `store` instance this way instead of getting store `dispatch` through props. – Estus Flask Sep 13 '18 at 03:57

1 Answers1

0

Importing the action creator, like import { sendInfo } from '../actions/index';, is fine - that's how you're supposed to do it.

However, you should then use connect to "bind" the action creators so that they access the correct store instance at runtime and dispatch the action automatically. This can be made shorter by using the "object shorthand" syntax - just pass an object full of action creators as the second argument to connect, like:

export default connect(null, {sendInfo})(SendInfoButton);

Similarly, you shouldn't import the store directly. As @estes said, that locks your code into the same "production" store instance all the time, and makes it harder to test or reuse your code.

markerikson
  • 63,178
  • 10
  • 141
  • 157