0

I'm using react-native-dropdown-picker to create two drop downs.

Everything is housed within a Form component. The first dropdown component is a list of sites, and once a site is selected, will pass the site back to the Form component and get the list of buildings associated with this site. These buildings is passed via state to the second form, but I'm having trouble with this final step of updating the state for the second dropdown. The dropdown component accepts the item as a state variable. What could I do to make this work?

Pseudocode:

import ...

class Form extends React.Component {
    constructor(props){
        super(props)
        // various data preprocessing steps
        this.siteDropdownData = [...];
        this.state = {
            buildingDropdownData: []
        }
    }

    siteUpdated(site) {
        await this.setState({siteSelected: site});
        await this.updateBuildingDropdownData();
    }

    async updateBuildingDropdownData() {
        // site and building data processing
        // can confirm that the state updates with new data
        await this.setState({buildingDropdownData: dropdownData})
    }

    render() {
        return (
            <View>
                <DropDownSelect
                    selection="site"
                    callback={this.siteUpdated}
                    items={this.siteDropdownData}
                />
                
                // this component renders when a site is selected but does not get passed the new dropdown data
                {this.state.siteSelected != null &&
                    <DropDownSelect
                        selection="building"
                        items={this.state.buildingDropdownData}
                    />
                }
            </View>
        );
    }
}

I've tried dispatches, passing the data as a prop, as a state variable, and nothing seems to work. It just uses the initialized data (an empty array), and never updates.

ayylamow
  • 13
  • 3

1 Answers1

0

The problem is that you shouldn't use await with this.setState. Convert your async function to synchronous functions and remove the await.

Numan Ijaz
  • 878
  • 1
  • 8
  • 18
  • I see now that you're not supposed to await setState(), however removing async/await causes no building data to be set in `updateBuildingDropdownData()` I can apply [this solution](https://stackoverflow.com/questions/51968714/is-it-correct-to-use-await-setstate) to use it properly, however my original problem still remains. – ayylamow Mar 16 '23 at 21:52