2

I'm using a material dropdown in my application

<Dropdown 
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
/>

I fetch JSON object like this and it works fine.

  fetch('url', {  
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      username : "admin"
    })
  }).then((response) => response.json())
  .then((responseJson) => {
    var count = Object.keys(responseJson.message.Obj).length;
    for(var i=0;i<count;i++){
      console.log(responseJson.message.Obj[i].name) // I need to add 
      //these names to dropdown
    }
  })
  .catch((error) => {
    console.error(error);
  });

Now I need to add the responseJson.message.Obj[i].name values to my dropdown list.

1
  • Where are you calling fetch from ? Commented Mar 3, 2018 at 10:30

5 Answers 5

12
+25

Supposing that you're using react-native-material-dropdown.

Example:

Dropdown component should be rendered as follows:

<Dropdown
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
  data={this.state.drop_down_data} // initialise it to []
/>

Request code:

fetch('url', {
  ...
}).then((response) => response.json())
.then((responseJson) => {
  var count = Object.keys(responseJson.message.Obj).length;
  let drop_down_data = [];
  for(var i=0;i<count;i++){
    console.log(responseJson.message.Obj[i].name) // I need to add 
    drop_down_data.push({ value: responseJson.message.Obj[i].name }); // Create your array of data
  }
  this.setState({ drop_down_data }); // Set the new state
})
.catch((error) => {
  console.error(error);
});

Doc:

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to fill dropdown when you do scroll down? i mean a scroll infinity
How to take the selected value from drop down list?
You can use the value props to get the selected value as it is explained in the doc.
2

You can achieve this by using react native "state". Create a state then assign it to Dropdown component's data property. Then set responseJson.message.Obj[i].names to the state by using "this.setState()" method.

1 Comment

I did that by referring stackoverflow.com/q/42029477/8590807 this answer. but now it shows object is null or undefined.
2
  • Find out what is the shape of the data property needed (i.e. Array of Objects) for the <Dropdown /> component you are using
  • Make fetch calls inside componentDidMount
  • Treat the state of your component as if it were immutable (do not push directly to this.state. dropdownData)

Here is some sample code using react-native-material-dropdown:

    class Example extends React.Component {
       // Use constructor to assign initial state
       constructor(props) {
         this.state = {
           dropdownData: []
         };
       }

      componentDidMount() {
        fetch('url', {  
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username : "admin"
          })
        })
        .then((response) => response.json())
        .then((responseJson) => {
          var count = Object.keys(responseJson.message.Obj).length;
          // We need to treat this.state as if it were immutable.
          // So first create the data array (tempDataArray) 
          var tempDataArray = [];
          for(var i=0;i<count;i++){
            // Note: react-native-material-dropdown takes an Array of Objects
            tempDataArray.push({
              value: responseJson.message.Obj[i].name
            });
          }
          // Now we modify our dropdownData array from state
          this.setState({
            dropdownData: tempDataArray
          });
        })
        .catch((error) => {
          console.error(error);
        });
      }

      // ...
      render() {
        return (
          // ...
          <Dropdown 
            baseColor='white'
            itemColor='white'
            label='Select Cluster'
            data={this.state.dropdownData} // Use dropdownData for the data prop
          />
          // ...
        );
      }
      // ...
    }

See: AJAX Requests in React

See: react-native-material-dropdown expected data type

Comments

1

Sample code

import React, { Component } from 'react';

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

export default class AddInventory extends Component {

 constructor(props)
 {

   super(props);

   this.state = { 

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

      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);
        });
    }

    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
}

});

Comments

0

You could also take an approach like this:

var Somedata = {
            "data" : [
                {
                "baseColor": "white",
                    "moreData":[
                        {
                            "id" : 118,
                        }
                    ]
                },
                {
                "baseColor": "grey",
                    "moreData": [
                        {
                            "id": 1231231,
                        }
                    ]
                }
            ]
        }
const renderData = someData.data.map((data) => {
        return data.moreData.map(brand => {
            strColor = data.baseColor;
            console.log("Individual Data :" + strColor)
                return `${data.baseColor}, ${moreData.id}`
                //setState here?
        }).join("\n")
    }).join("\n")
//setState here?

You now have a few options you could set the state. From your example, you would set the state the state of your list to the data returned from the fetch call once it has been rendered. A quick thing to keep in mind is that react doesn't support asynchronous loading currently. Therefore the data must be rendered as empty, or with some sample data and then updated once the call has been made to whatever you wish to update! Hope this helps a little :) https://reactjs.org/docs/faq-ajax.html

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.