1

I want to fetch multiple API requests in componentDidMount() function. I have a picker which take items from API call. I have another API which returns a picker value. Now i want to set selected the value received in latter API in the picker. I am trying to fetch both API in componentDidMount function
Here is my code. Please suggest where i am missing.

import React, { Component } from 'react';

import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';

export default class FirstProject extends Component {

 constructor(props)
 {

   super(props);

   this.state = { 

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

  const base64 = require('base-64');

// my  API which fetches picker items 
      return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
        .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);
        });

  // another api which fetches a particular fruit_id from database which i ave to set selected in picker.
fetch('http://my_api_url', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "fruit_id":"123"
  })
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        PickerValueHolder: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
    }

    GetPickerSelectedItemValue=()=>{

      Alert.alert(this.state.PickerValueHolder);

    }

 render() {

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

   return (

    <View style={styles.MainContainer}>

          <Picker
            selectedValue={this.state.PickerValueHolder}

            onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >

            { this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
            )}

          </Picker>

          <Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />

    </View>

   );
 }
}

const styles = StyleSheet.create({

MainContainer :{

justifyContent: 'center',
flex:1,
margin: 10
}

});
11
  • What's the problem with your code? Commented Dec 7, 2017 at 6:13
  • It is not selecting the value obtained in second API in picker by default. Commented Dec 7, 2017 at 6:16
  • What's your second API response? Commented Dec 7, 2017 at 6:22
  • It contains a json array which contains values related to the fruit_id. [{"fruit_id": "123","fruit_name":"Strwaberry"}] Commented Dec 7, 2017 at 6:26
  • you should not use setState inside render method. Commented Dec 7, 2017 at 6:30

1 Answer 1

1

As you said in comment, your second API response:

[{"fruit_id": "123","fruit_name":"Strwaberry"}]

So it might work with minor changes:

.then((responseJson) => {
  this.setState({
    isLoading: false,
    PickerValueHolder: responseJson[0].fruit_name,
  }, function() {
    // In this block you can do something with new state.
  });
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.