0

actully,while updating a variable in react we are using set state.but using the setstate value is not updated still showing previous value.if i understand anything wrong in react.pls help me to understand. anyone help me..how to update state in reactJS..

//HTML CODE for select
<select onChange={changeSelect}>
        <option value="1">City 1</option>
        <option value="2">City 2</option>
        <option value="3">City 3</option>
      </select>


//below method will trigger while selecting value in html

const changeSelect=(e)=>{
    console.log("value from dropdown",e.target.value);
     setSelectedCity(e.target.value);
     //ony previous value is coming..
     console.log("value in the variable "+selectedCity)

  }

below image is console screenshot of browser

enter image description here

prasanth
  • 22,145
  • 4
  • 29
  • 53
Praveen Kumar
  • 29
  • 1
  • 3

1 Answers1

0

setState is asynchronous. Do what you want with the updated value in a side effect.

Move your console.log in a useEffect:

useEffect(() => {
  console.log(selectedCity)
}, [selectedCity])
HichamELBSI
  • 1,712
  • 13
  • 19