1

I have the following code using React Hooks and MUI Select component.

<Select variant='outlined' 
        value={plan} 
        onChange={setPlanAndAmount} 
        style={{ width: '98%' }} >
  <MenuItem value={'bronze'} >Bronze</MenuItem>
  <MenuItem value={'silver'} >
    Silver
  </MenuItem>
  <MenuItem value={'gold'} >
    Gold
  </MenuItem>
</Select>

The onChange handler is:

 const setPlanAndAmount = (e) => {
   setPlan(e.target.value)

   switch(plan) {
       case 'bronze':
         setGiftingAmount('99.99')
         break;
       case 'silver':
         setGiftingAmount('199.99')
         break;
       case 'gold':
         setGiftingAmount('299.99')
         break;
       default:
         setGiftingAmount('99.99')
         break;         
       }
  }

What is does is that it takes the plan, runs it through a SWITCH statement and sets the giftingAmount which is used elsewhere. What the problem is the first time I select a plan, nothing happens but the next time I'm doing it it returns the previous value instead on the current one.

What's the solution for this??

ikos23
  • 4,879
  • 10
  • 41
  • 60
HASEEB Ahmed
  • 109
  • 3
  • 12

1 Answers1

1

This is happening because of the updater provided by useState is asynchronous, since state values relies on closure and changes on next re-render. Check this for more detail: https://stackoverflow.com/a/54069332/9119053

You can try doing this:

 const setPlanAndAmount = (e) =>{
const updatedPlan = e.target.value;
        setPlan(updatedPlan)

        switch(updatedPlan){
            case 'bronze':
                setGiftingAmount('99.99')
                break;
            case 'silver':
                setGiftingAmount('199.99')
                break;
            case 'gold':
                setGiftingAmount('299.99')
                break;
            default:
                setGiftingAmount('99.99')
                break;         
        }
    }

Or use useEffect to update giftingAmount

Yash Joshi
  • 2,586
  • 1
  • 9
  • 18