Saphire
Saphire

Reputation: 1930

How to use props for method in mapDispatchToProps?

I want to use props I get through mapStateToProps in mapDispatchToProps. How can I do that?

const mapStateToProps = (state) => {
  return {
      resultItems: res,
      loading: state.loading,
      lastQuery: state.lastQuery,
      selectedCat: state.selectedCat
  }

};

const mapDispatchToProps = (dispatch, ownProps) => ({
    sendClickedQuery(selectedCat) {

        // Use props as parameters here
        dispatch(mutations.sendQuery(lastQuery, selectedCat));
    }
});

export const ConnectedMain = connect(mapStateToProps, mapDispatchToProps)(Main);

Upvotes: 0

Views: 37

Answers (1)

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You can use mergeProps which is an optional parameter of connect like:

const mapStateToProps = (state) => {
  return {
      resultItems: res,
      loading: state.loading,
      lastQuery: state.lastQuery,
      selectedCat: state.selectedCat
  }

};

const mapDispatchToProps = (dispatch, ownProps) => ({
    sendClickedQuery(selectedCat) {
        dispatch(mutations.sendQuery(lastQuery, selectedCat));
    }
});

const mergeProps = (propsFromState, propsFromDispatch) => (
    {
      ...propsFromState,
      ...propsFromDispatch,
      sendQuery: propsFromDispatch.sendClickedQuery(selectedCat) {
        dispatch(mutations.sendQuery(propsFromState.lastQuery, selectedCat));
    }
    }
  );

export const ConnectedMain = connect(mapStateToProps, mapDispatchToProps, mergeProps)(Main);

And now you can call it like props.sendQuery. Hope this works for you.

Upvotes: 1

Related Questions