Home > OS >  How to set value to picker from api in react native?
How to set value to picker from api in react native?

Time:10-15

In the below code I have to use the picker. I want to add value from API. I got the value from API but it does not reflect on the picker value please help me to solve this problem. I know it's a minor error but I am new in the react-native so sorry for this silly question.

import React, { Component, useState } from "react";
        import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
        import { Picker } from "@react-native-picker/picker";
        import { PickerItem } from "react-native/Libraries/Components/Picker/Picker";

        class VolunteerPage extends Component {
            constructor(props) {
                super(props);

                this.state = ({
                    stateList: []
                });
            }

            componentWillMount() {
                this.getdata();
            }

            getdata() {
                var temp = [];
                const url = "https:www.example.com";

                fetch(url, {
                    method: 'POST',
                    headers: new Headers({'Content-Type': 'application/json'})
                })
                .then(res => res.json())
                .catch(error => console.error('Error : ', error))

                .then((response) => {
                    console.log("Response : ",response);
                    var length = response.state.length;
                    console.log("Length of State is : ",length);
                    if (length > 0) {
                        for (let i = 0; i < length; i  ) {
                            var data = response.state[i];
                            var joined = { value: data.amd_state };
                            temp.push(joined);
                        }
                    }
                    this.setState({
                        stateList: temp
                    });
                })
            }
            render() {
                return (
                    <View>
                        <Picker} onValueChange={(itemValue, 
                        itemIndex)=>this.setState((stateList.itemValue))}>
                            <Picker.Item label="Select State" value="this.state.stateList" />
                        </Picker>
     
                        <TouchableOpacity style={styles.TouchableOpacity} onPress={() => this.apiCallHere()}>
                            <Text style={{ color: "white" }}>Next</Text>
                        </TouchableOpacity>
                    </View>
                )
            }
        }
        

        export default VolunteerPage

CodePudding user response:

I think your error is here:

 <Picker} 
  onValueChange={
    (itemValue,itemIndex)=>
     this.setState((stateList.itemValue)_
   }
  >
     <Picker.Item label="Select State" value="this.state.stateList" />
 </Picker>

I think you want it to be:

 <Picker 
   onValueChange={ (itemValue,itemIndex)=>
     this.setState({stateList:itemValue})
   )}
 >
   <Picker.Item label="Select State" value={this.state.stateList} />
 </Picker>

CodePudding user response:

Sorry I didn't really understand what was going on with state list after your api call. I would add an additional value to your state selectedIndex to keep track of what is currently selected. So your constructor would look like

constructor(props) {
  super(props);
  this.state = ({
    stateList: [],
    // -1 or default selection value
    selectedIndex:-1
  });
}

Then make use of the map function of the array class to render all of your stateList options:

<Picker 
   onValueChange={ (itemValue,itemIndex)=>
     this.setState({selectedIndex:itemIndex})
   )}
 >
   {this.state.stateList.map( (value,index)=> (
     <Picker.Item
       {/*
       Here I use a generic name, but you could use the 
       value of the value if you wish
       */}
       label={"Option " (index 1)}
       value={value}
     />
   )}
 </Picker>
  • Related