PrEto
PrEto

Reputation: 405

Is it possible to call action from components function?

I have question is there any possibility to call actions from function or event handler? I use React-Redux.

Example:

    export class Page extends React.Component {

    onSomething() {
        this.props.onAdd();
      };

    render() {
        return (
             <div>
               <List
                 SomeMethod={this.onSomething};
               />
             </div>
           );
         }
    }

    Page.propTypes = {
      onAdd: PropTypes.func,
    };

    export function mapDispatchToProps(dispatch) {
      return {
        onAdd: evt => {
          dispatch(fetchAdd());
        },
      };
    }

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

const withReducer = injectReducer({ key: 'page', reducer });
const withSaga = injectSaga({ key: 'page', saga });

export default compose(
  withReducer,
  withSaga,
  withConnect,
)(Page);

I am getting error, that: Uncaught TypeError: Cannot read property 'onAdd' of undefined

Maybe someone know what I am doing bad?

Upvotes: 1

Views: 39

Answers (1)

Icepickle
Icepickle

Reputation: 12796

You are just lacking the this context in your onSomething function. You can bind it either in the constructor, through class properties or as an arrow function in your jsx

export class Page extends React.Component {
  constructor() {
    this.onSomething = this.onSomething.bind(this);
  }
  // ...
};

or class properties (needs babel-plugin)

export class Page extends React.Component {
  onSomething = () => {
    this.props.onAdd();
  }
  // ...
};

or through arrow function in JSX

render() {
  return (
    <div>
      <List
        SomeMethod={() => this.onSomething()};
      />
    </div>
  );
}

Upvotes: 2

Related Questions