hitttt
hitttt

Reputation: 1189

add API data values in Picker react native

I am new to react native. I want to add values from database into picker using API please suggest how can i do that.

componentDidMount() {

    return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
      .then((response) => response.json())
      .then((responseJson) => {
        let ds = new Picker.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(responseJson),
        }, function() {
          // In this block you can do something with new state.
        });
      })
      .catch((error) => {
        console.error(error);
      });
    }

Here is my picker in which i need to insert the values that are fetched from API function componentDidMount()

render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

      <View style={styles.MainContainer}>
<Picker
  selectedValue={this.state.active}
  dataSource={this.state.dataSource}
  onValueChange={(activeValue, activeIndex) => this.setState({active: 
    activeValue})}>
  renderRow={(rowData) => <Picker.Item label={rowData.fruit_name} value=
   {rowData.fruit_name} />} 
    </Picker>
      </View>
    );}}

Upvotes: 3

Views: 6175

Answers (1)

hitttt
hitttt

Reputation: 1189

Found a solution here :- https://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/

Here is the code snippet :-

componentDidMount() {
  const base64 = require('base-64');
return fetch('http://your_api_url', {
  method: 'POST',
  headers: {
    "Authorization": "Basic " + base64.encode("user:passwd")
  }
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
}

And below code is where we add it in a Picker.

render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

      <View style={styles.MainContainer}>
<Picker style={styles.PickerStyleClass}
        selectedValue={this.state.mode}
        onValueChange={(modeValue, modeIndex) => this.setState({mode: modeValue})}>
    {this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item} value={item} key={key} />)
            )}
</Picker>
      </View>
    );}}

Upvotes: 3

Related Questions