Pointer
Pointer

Reputation: 2186

Parse json react native

I'm using crypto api to load data in my app. How render price in my example?

I'm try {item.quotes.price} but not working any solution?

My source code is:

export default class FetchExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLoading: true };
  }

  componentDidMount() {
    return fetch("https://api.coinmarketcap.com/v2/ticker/?start=1&limit=10&sort=id&structure=array")
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: responseJson.data
          },
          function() {

          }
        );
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item }) => (
            <Text>
              {item.name}, {item.symbol}
            </Text>
          )}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

Any solution?

Tnx all for help!

Upvotes: 2

Views: 5379

Answers (1)

Tholle
Tholle

Reputation: 112777

The data you get from your request has the price under item.quotes.UDS.price, not item.quotes.price.

Also make sure that you initialize an empty dataSource array in your state:

class FetchExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLoading: true, dataSource: [] };
  }

  componentDidMount() {
    return fetch("https://api.coinmarketcap.com/v2/ticker/?start=1&limit=10&sort=id&structure=array")
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.data
        });
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item }) => (
            <Text>
              {item.name}, {item.symbol}, {item.quotes.USD.price}
            </Text>
          )}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

Upvotes: 2

Related Questions