Best Sports
Best Sports

Reputation: 11

getting undefined selected value from dropdown in react native

I am new to learn react native. I want to get selected value from dropdown in react-native.

my constructor

constructor(props){
      super(props);
      this.state = ({       
        PickerSelectedVal : ''
      })
}

in render

render(){
      <Dropdown                 
                label="Select"
                options={["Op1","Op2"]}                     
                selectedValue={this.state.PickerSelectedVal}
                onSelect={(obj)=>this.changedemo({obj})}
      />
}

in function

 changedemo= (ob)=>{
      this.setState({PickerSelectedVal : ob});
      alert("Selected country is : " +ob.PickerSelectedVal);
      console.log(this.state.PickerSelectedVal);
      if (this.state.PickerSelectedVal === 1) {
          alert("Selected value is : " +ob.PickerSelectedVal);
      } 
      if(this.state.PickerSelectedVal === 0) {
alert("Selected value is : " +ob.PickerSelectedVal);
      }

  }

I have tried many times. I want to get selected value from dropdown alert is also showing but it prints. Selected value is:undefined.

Upvotes: 1

Views: 371

Answers (2)

Karishma Kavankar
Karishma Kavankar

Reputation: 100

your changedemo function must be like following;

  changedemo= (ob)=>{
      this.setState({PickerSelectedVal : ob.value});
      alert("Selected country is : " +ob.value);
      console.log(ob.value);
      // rest of the code
  }

Upvotes: 0

Pramod
Pramod

Reputation: 1940

setState is a async process so when you are printing it by that time the state is not yet set. Add This

this.setState({PickerSelectedVal : ob},()=>{console.log(this.state.PickerSelectedVal)});

Upvotes: 1

Related Questions