How do I set get the specific array index of JSON response array to TextInput in React Native

1000 Views Asked by At

I am able to fetch my complete response in react native the code is as follow to fetch the data

import React, { Component } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  FlatList,
} from 'react-native';


export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
    }
  }

  componentDidMount() {
    let content = '/LoginPageLoad_Arr';
    const url = 'abc.asmx' + content;
    fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
      },
    })
      .then((response) => response.json())
      .then((responseJson) => {
        const result = JSON.parse(responseJson.d)

        this.setState({
          dataSource: result.Table1
        })
      }).catch((error) => {
        console.error(error);
      });
  }
  _renderItem = ({ item }) => (
    <TouchableOpacity>
      <View>
        <Text>
          {item.ID} = {item.VALUE}
        </Text>
      </View>
    </TouchableOpacity>
  )
  render() {
    return (
      <View>
        <FlatList
          data={this.state.dataSource}
          renderItem={this._renderItem}
        // keyExtractor={(item, index) => index}
        />
      </View>
    )
  }
}

enter image description here

My concern is to fetch the ID and VALUE at the index 0. I tried adding the code item.ID[0] it just fetch me the first letter of all the ID. I want complete complete ID at just index 0 to set in TextInput. Please if someone as worked on it help me out.

1

There are 1 best solutions below

0
Thomas Neveu On BEST ANSWER

First, better method is to cut your function in ComponentDidMount, and use async instead of .then() like :

ComponentDidMount(){
  this.callApiFunction();
}

async callApiFunction(){
  try{
    let content = '/LoginPageLoad_Arr';
      const url = 'abc.asmx' + content;
      const call = await fetch(url, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json; charset=utf-8',
        },
      })
        call = call.json();
        call = JSON.parse(call.d)
        //If you want to browse an array, you can use the map function
        call.map((item, index) => {
        //And make condition here, for exemple the first element
        if(index == 0){
            //DO what u want 
            console.log(item)
            this.setState({
            dataSource: item
          })
        }
        
        })
          
        }).catch((error) => {
          console.error(error);
      });
    }
    catch(e){
      console.log(e)
    }
}

Hope it will help you