Redux action not present

Viewed 686

I have set up correctly according to doc redux boilerplate. I have a folder of various action files which contains actions. In this folder I have created an index.js where I am exporting all these files. I import it as named export. When I console log the function itself it is there, but when I console log out this.props its not present. I have tried to console log out the function outside the class its undefined.

If I import the action directly from the file it is defined in it works.

actions/formActions.js

export const formInput = (key, val) => (
    {
        type: FORM_INPUT,
        payload: { key, val }
    }
);

actions/index.js

export * from './formActions';

FormComp.js

import { formInput } from './actions'; //  <-- this.props.formInput = undefined 

or

import { formInput } from './actions/formActions'; //  <-- this.props.formInput = func 

connect:

class InputField extends Component { ... }

const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);

export { FormComp };

edit1: If I inside componentWillMount() console.log(formInput) //without this.props its there.

edit2 (solution?): I was able to map actions to props with bindActionCreators. How ever I don't understand why I need to use bindActionCreators and why I can't just export connect as it is with actions as second param.

const FormComp = connect(
  ({ forms }) => ({ forms }), 
  dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);
2 Answers

The reason this.props.formInput is not defined but formInput is defined is because the redux connect is not properly setting the function formInput against the variable(property) formInput within the component props.

  1. formInput is the function you are importing,
  2. this.props.formInput is the property that should "point" to the function you import.

Try (I have separated out for clarity)

function mapStateToProps(state) {
    return {
      forms: state.forms
    }
  }
function mapDispatchToProps(dispatch) {
  return {
    formInput: (key, val) => dispatch(formInput(key val))
  };
}

export connect(
  mapStateToProps, 
  mapDispatchToProps
)(InputField);

Then anywhere in your code you call

this.props.formInput(key, val);

This will call the action via props, and therefore will dispatch. properly

You need to return a function which has dispatch and getState as parameter.

export const formInput = (key, val) => (dispatch, getState) => {
    // maybe additional stuff
    dispatch({
        type: FORM_INPUT,
        payload: { key, val }
    });
};

See title Action Creators from the documents: https://redux.js.org/docs/basics/Actions.html

Related