xploshioOn
xploshioOn

Reputation: 4115

how to fill picker (android) of react native with fetch

I have a picker in my app and i want to fill this with data fetched in the server, I have the data in a state of the app, but I don't know how to make the app to update the picker when the data is fetched

constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      client: '',
      clients: null
    };
  }

componentDidMount() {
    this.fetchData();
  }

I have this in my view

<Picker
              style={styles.picker}
              itemStyle={styles.items}
              selectedValue={this.state.client}
              onValueChange={(cli) => this.setState({client: cli})}
              prompt="Seleccione un cliente" >
              <Picker.Item label="Cliente 1" value="1" />
              <Picker.Item label="Cliente 2" value="2" />
              <Picker.Item label="Cliente 5" value="5" />
              <Picker.Item label="Cliente 4" value="4" />
              <Picker.Item label="Cliente 3" value="3" />
              <Picker.Item label="Cliente 9" value="9" />
              <Picker.Item label="Cliente 8" value="8" />
            </Picker>

and the fetchData function

fetchData() {
    var baseURL = 'http://192.168.100.11:3000/clients';
    fetch(baseURL, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    })
        .then((response) => response.json())
        .then((responseData) => {
          if(responseData.message){
            this.setState({isLoading: !this.state.isLoading});
            alert(responseData.message);
          }else{
            this.setState({isLoading: !this.state.isLoading, clients:responseData});
          }
        })
        .done();
  }

the thing is how can I make the picker update when the data is fetched. thanks

Upvotes: 6

Views: 5591

Answers (1)

Frederick Motte
Frederick Motte

Reputation: 1164

You should set the picker items based on your state by mapping them, for example:

<Picker style={styles.picker}
        itemStyle={styles.items}
        selectedValue={this.state.client}
        onValueChange={(cli) => this.setState({client: cli})}>
            {this.state.clients.map((l, i) => {return <Picker.Item value={l} label={"Cliente " + i} key={i}  /> })}
    </Picker>

When you receive the data from fetch, you just update the state of "clients", as you are doing, and the picker items will be updated automatically.

An example can be found here where the items are updated based on clicking the button: https://rnplay.org/apps/XfkfnQ

Upvotes: 4

Related Questions