简体   繁体   中英

How to pass picker data into API in React Native

I built a React Native Component that lets you choose several types of beers and it will render into a listview with picker.

The problem I am having trouble grasping is sending that data into the BreweryDb Api. I am not sure where to start with this semi completed component.

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet, ListView } from 'react-native'

const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});

export default class BeerPicker extends Component {
    constructor(props){
      super(props);

      this.state = {
        beer: [],
        beerDataSource: ds.cloneWithRows([]),
        dataSource: ds.cloneWithRows(['string1', 'string2', 'string3']), //It seems to be not needed...
        items: [
          {label: 'Choose Beer', value: 'none'}, 
          {label: 'IPA', value: 'ipa'}, 
          {label: 'Pilsner', value: 'pilsner'}, 
          {label: 'Stout', value: 'stout'}
        ],
        selectedItem: 'none'
      };

      this.addBeer = this.addBeer.bind(this);
    }

    addBeer(itemValue, itemIndex){ 
      let newBeerArray = [...this.state.beer, itemValue];
      this.setState({
        beer: newBeerArray,
        selectedItem: itemValue,
        beerDataSource: ds.cloneWithRows(newBeerArray),
      });
    }

    renderRow(data) {
      return (
        <Text>{`\u2022 ${data}`}</Text>
      );
    }

    render() {
      let items = this.state.items.map((item, index) => {
        return (<Picker.item label={item.label} value={item.value} key={index}/>);
      });

      return (
        <View>
          <Picker selectedValue={this.state.selectedItem} onValueChange = {this.addBeer}>
            {items}
          </Picker>
          <ListView
            dataSource={this.state.beerDataSource}
            renderRow={this.renderRow}/>
        </View>
      )
    }
}

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'black'
   }
});

I want to use each selected item and loop through the API several times to get information on each picked item.

You can do it several ways. If you want to make an api call when user selects a new beer then the following code may be helpful:

add apiData: {} to initial state

add this.fetchBeerFromApi(itemValue); in the addBeer function

// notice I used es7 fat arrow functions to avoid having to bind in constructor
fetchBeerFromApi = async (beerId) => {
  let response = await fetch(`${BREWERY_API_URL}/beer/${beerId}`);
  response = await response.json();

  if (response.error) {
    console.error('Error with brewery api beer request', response.error);
    return false;
  }
  const apiData = this.state.apiData;
  apiData[beerId] = response;
  // Or handle storing apiData somewhere else... I usually use immutable data
  // structures to avoid deeply nested data not triggering re-rendering issues
  // so this may or may not be problematic...
  // Here is the immutablejs alternative to those last two lines:
  // const apiData = this.state.apiData.set(beerId, response);

  // Here we store it back to state where you can handle rendering the data if
  // it is available
  this.setState({apiData});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM