Ankur Verma
Ankur Verma

Reputation: 5933

Passing state value to mapDispatchToProps in React Redux

DISCLAIMER: I just started learning React and Redux, so may be this is a noob question, but please bear with me.

So, here is the short form of my problem:

import { connect } from 'react-redux'
import someComponent from 'some_file_that_exports_component_as_default_export' 

const mapStateToProps = state => ({ state })

const mapDispatchToProps = (dispatch, ownProps) => ({
    fetchComplianceLink() {
     dispatch({
      type: 'ACTION_TYPE',
      payload: {
        someKey: <XYZ>, // --> this value (XYZ) I want from my state
      },
     })
    },
})

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(someComponent)

I tried with mergeProps as well, but didn't get any success. May be my approach is wrong, or may be mergeProps is not the function that might fix this. Please shed some light. How could I get the value of XYZ from state

Thanks in Advance & Happy Coding :)

Upvotes: 0

Views: 348

Answers (1)

thortsx
thortsx

Reputation: 2280

You can not pass state of store (dynamic state) to mapDispatchToProps, It just return an object have functions that you define and help you how to dispatch and what dispatch to do. You need to do:

const mapStateToProps = state => ({
    key: state... // get value of store here to pass into Component
})

const mapDispatchToProps = dispatch => ({
    fetchComplianceLink(value) {
        dispatch({
           type: 'ACTION_TYPE',
           payload: {
               // someKey: <XYZ>, // --> this value (XYZ) I want from my state
               someKey: value
           },
        })
    },
})

Use fetchComplianceLink in Component:

ComponentDidMount() { // or ComponentWillMount
    const { key, fetchComplianceLink } = this.props;
    // Call fetchComplianceLink with key got from store
    fetchComplianceLink(key);
}
render () {
    return (

    )
}

Upvotes: 2

Related Questions