React-Native: How to Integrate API in different Situations

Hello guys, while integrating API in react-native we usually face many problems, like fetching the data from API and work with that data on same page, some times we need to show the list of items in List-view, and sometimes we need to pass the object from the render function into the functions which you are calling outside the render function.

Lets’ start with the easy one, in which we just have to show the data coming from API into the page where you don’t have any type of looping, like just wants to display the description of single item.

Before going into the coding, hope you are clear with the concepts of state and props.

We use state to store the data your current page needs in your controller-view, and we use props to pass data & event handlers down to your child components.

As the uses define we need to store the data on our current page so we will use the state.

Example:

import React ,{Component} from 'react';  
 import {  
  View,  
  Text  
 } from 'react-native';  
 import axios from 'axios';  
 export default class classname extends Component{  
   state={  
   customerDetail:[] 
  }  
  componentDidMount() {  
  axios.get('API')  
  .then(response => this.setState({  
   customerDetail : response.data,  
  }))  
  .catch(function(err) {  
    return err;  
   });  
  }  
  render() {  
   console.log(this.state.customerDetail) //this will display the response of API 
    return (  
     <View>  
        <Text>{this.state.customerDetail.name}</Text>  
     </View>  
    )  
 }  

The above code will fetch the dictionary and will store it in customerDetail state and we can call its objects with dot (.) operator as done the above code and that  can be used in the render function.

For the other two situations I will continue in other blog.

 

Leave a comment

Website Powered by WordPress.com.

Up ↑