-1

I have a component where i make an order estimation calculation ( a multiplication of quantity for his price ) in two cases

1) In the lifecycle method

componentDidMount(){
  if (this.props.isRestarted) {
    this.setState({
          orderEstimation: this.props.formData.valNominal * this.props.formData.priceLimit,
   })
}

2) In an Event

<FormAmountField
    label={}
    placeholder={}
    value={this.state.price}
    onChangeText={(value) => {
    this.setState({
        price: value,
        orderEstimation: parseFloat(value) * parseFloat(this.state.quantity)
    })
}}

As you can see in both cases: orderEstimation: parseFloat(value) * parseFloat(this.state.quantity)

I have a case when this.props.selectedTitleDetails.exchangeHost == "THIS_TEXT" i want the the calculation changing parseFloat(value) * parseFloat(this.state.quantity) / 100

How can i apply this change in both cases? in the life cycle and the method?

Koala7
  • 1,340
  • 7
  • 41
  • 83
  • Why don't you use a function with Switch cases in it. [enter link description here](https://stackoverflow.com/questions/46592833/how-to-use-switch-statement-inside-a-react-component/46593006) – deepanshu Jun 18 '20 at 08:56

1 Answers1

1

You can use a variable of state to mark - exchangeValue. Example:

constructor() {
    this.state = {
        exchangeValue: 1
    }
}

componentDidUpdate(prevProps) {
     if (prevProps.selectedTitleDetails.exchangeHost !== this.props.selectedTitleDetails.exchangeHost 
         && this.props.selectedTitleDetails.exchangeHost === 'THIS_TEXT') {
          this.setState({
               exchangeValue: 100
          })
     }
}

Then you add this.state.exchangeValue into the your calculation

componentDidMount(){
  if (this.props.isRestarted) {
    this.setState({
          orderEstimation: this.props.formData.valNominal * this.props.formData.priceLimit / this.state.exchangeValue,
   })
}

And

onChangeText={(value) => {
    this.setState({
        price: value,
        orderEstimation: parseFloat(value) * parseFloat(this.state.quantity) / this.state.exchangeValue
    })
}}
Ryan Nghiem
  • 2,417
  • 2
  • 18
  • 28