1

I am new to ReactJS. I am trying to use ReactJS and redux together.

  1. Can anybody explain how to connect the two?

  2. Also, in redux reducer, we usually set the intialState to some value. How can I set the value which is already present in react component's state to the initialState of reducer?

Below is initialization done in my reducer,

const initialState = {
    pricing:{
        total:0
    },
    appliedPromo:false
}

Below is my state in react component,

state = {
    pricing: {},
    itemDetails: {},
    error: false,
    seeDetails:false,
    showPromoCode:false,
    promocodeApplied:false,
    user_discount:""
  }

I will update the state using axios,

componentDidMount() {
axios
      .get("https://purchsum-fb152.firebaseio.com/data.json")
      .then(response => {
        this.setState({ pricing: response.data.Pricing, itemDetails: response.data.itemDetails });

      })
      .catch(error => {
        this.setState({ error: true });
      });   
}

then I will connect state to props,

const mapStateToProps = (state) => {
  return{
    total: state.pricing.total,
    promoApplied: state.appliedPromo
}
}
const mapDispatchToProp = dispatch =>{
  return{
    onDiscount:()=>dispatch({type:"DISCOUNT",value:10,percentage:100})
  } 

}
export default connect(mapStateToProps,mapDispatchToProp)(PurchaseOrder); 

The application works only if i set initialState as following,

const initialState = {
    pricing:{
        total:108.03
    },
    appliedPromo:false 
}

I don't want to set it (no hard code). Instead I want reducer to take state value which is updated in the component.

Josh Pittman
  • 7,024
  • 7
  • 38
  • 66
  • Answered here https://stackoverflow.com/questions/34458261/how-to-get-simple-dispatch-from-this-props-using-connect-w-redux – Dupocas Mar 20 '19 at 22:44
  • 1
    Possible duplicate of [How to get simple dispatch from this.props using connect w/ Redux?](https://stackoverflow.com/questions/34458261/how-to-get-simple-dispatch-from-this-props-using-connect-w-redux) – Dupocas Mar 20 '19 at 22:44

1 Answers1

0

I don't want to set it (no hard code). Instead I want reducer to take state value which is updated in the component.

That's not the redux pattern unfortunately. You must set the intial state for the reducer to load up - I would not suggest that this can or should be done dynamically.

However, can you not create an action which will set the state to what you want when your Component mounts?

jsdeveloper
  • 3,945
  • 1
  • 15
  • 14