Search code examples
reactjsreact-nativecascadingdropdown

Update Dropdown list when a value is selected on another one


My code has two dropdown lists from "react-native-material-dropdown". The first one is populated at the start and the second one has to be populated (from fetching json data) when an element is selected on the first dropdown.

This is all I wrote so far:

...
import { Dropdown } from 'react-native-material-dropdown';

export default class Example extends Component {

  render() {
    let firstValues = [{
      value: 'AAA',
    }, {
      value: 'BBB',
    }, {
      value: 'CCC',
    }];

    return (
        <View>
          <Dropdown
            label='First'
            data={firstValues}
            onChangeText={(value)=>{
              fetch("...")
              .then(response => response.json())
              .then((responseJson)=> {
                var count = Object.keys(responseJson.myJson).length;
                let secondValues = [];
                for(var i=0;i<count;i++){
                  secondValues.push({ value: responseJson.myJson[i].name });
                }
                this.setState({ secondValues });
              })
              .catch((error) => {
                alert('Error');
              });
            }}
          />
          <Dropdown
            label='Second'
            data={this.secondValues}
          />
        </View>
    )
  }
}
...


The problem is that the second dropdown list never updates and it is always empty.
I'm still a beginner so any help would be appreciated.

Thanks.


Solution

  • In Second DropDown you are not getting the state value correctly

    Change this

    <Dropdown
      label='Second'
      data={this.secondValues}
    />
    

    to

    <Dropdown
      label='Second'
      data={this.state.secondValues}
    />