Fetching data from an API in react native
Today I am going to explain how to get JSON data objects from an API, this
would be very useful for every react native developer, and I tried to explain this
much as simpler I can.
· 1st lets create a react native project by using the command
o react-native init FetchData
In my example I named my project as FetchData, you can use any name you
want.
After generating the project, you can practice this lesson by editing App.js file, your App.js
file will look like this after you are generating it.
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
importReact, {Component} from'react';
import{Platform, StyleSheet, Text, View} from'react-native';
constinstructions = Platform.select({
ios: 'Press Cmd+R to reload,\n'+ 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n'+
'Shake or press menu button for dev menu',
});
typeProps = {};
exportdefaultclassApp extendsComponent<Props> {
render () {
return(
<Viewstyle={styles.container}>
<Textstyle={styles.welcome}>Welcome to React Native!</Text>
<Textstyle={styles.instructions}>To get started, edit App.js</Text>
<Textstyle={styles.instructions}>{instructions}</Text>
</View>
);
}
}
conststyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
· After you have to delete unwanted code segments in App.js file, your modified file would be look like this after deleting unwanted code segments.
importReact, { Component } from"react";
import{Platform, StyleSheet, Text, View } from"react-native";
exportdefaultclassApp extendsComponent<Props> {
render() {
return<Viewstyle={styles.container}/>;
}
}
conststyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
}
});
· Now you can do modifications to your app,1stwe have to modify
import{ Platform, StyleSheet, Text, View } from"react-native";
as
importReact, {Component}from"react";
import{
Platform,
StyleSheet,
Text,
View,
ActivityIndicator
} from"react-native"
· In here I added a component called ‘ActivityIndicator’ this indicator appears until current internal processing’s are over, in this example I demonstrated this indicator until the API fetch data. After that we have to implement our Constructor after our exported default class
exportdefaultclassApp extendsComponent {
constructor(props) {
super(props);
this. state = {
isLoading: true,
dataSource: [] //this in empty until we fetch data from an API
};
}
· In this code segment I have set my state isLoading to Boolean true --(isLoading: true), and data source as an empty array (dataSource: []), After we have to define a method for capturing API data, in my example I named my method as
componentDidMount(){}
· now we can implement our method,
componentDidMount () {
returnfetch ("https://jsonplaceholder.typicode.com/posts/1/comments")//Set API
. then (response=>response. json ()) //take the response from the API and
//convert them to json
. then(responseJson =>{
this. setState({
isLoading: false, // set datasource to movies
dataSource: responseJson //array of JSON objects
});
})
. catch (error=>{ //show errors on console
console.log(error); //print errors
});
}
· Here I created a method, and inside react fetch method I assigned our API URL, and convert API responds to a JSON objects. After, from setState () method I update the states (isLoading, dataSource), in the beginning out state wasisLoading: true, dataSource:[], but here I changed it to isLoading: false, and to dataSource I assign whole object set of JSON data dataSource:responseJson. If we want to update the state In react native we have to use setState () method,finally from, .catchwe can identify errors if there any error it will showing on the console.
render() {
if(this.state.isLoading) {
return(
<Viewstyle={styles.container}>
<ActivityIndicatorsize="large"color="#00ff00"/>
</View>
);
} else{
return(
<Viewstyle={styles.container}>
{this.state.dataSource.map(item =>{. //set values to separate array
return(. //Return values
<Viewstyle={styles.item}>
<Text>{item.name}</Text> //prints name objects
);
})}
</View>
);
}
}
}
· inside render() method there is an if statement. This if statement gets values of isLoading key.
if(this.state.isLoading) {
· isLoading value become true when there aren’t any date inside array, if there are no any data available in the array, ActivityIndicatorappears, and showing us a simple animation, if there are data inside the array, else part will iterate and inside else part we mapped our data source that means collection of JSON objects to a separate array.
and that map returns values, if you follow all above steps correctly , you will able to see API name data
conststyles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
item: {
height: 40,
alignContent: "center",
justifyContent: "center",
borderBottomWidth: 1,
borderBottomColor: "#eee"
}
});
· Here is our Style sheet, from this we can design our Frontend interactively
Conclusion
today i explain how to get data from an API, i think this will be very useful for persons who like react native. if you want to be a react native developer you should know how to retrieve data from an API. and this blog will help you to understand this concept easily.

Comments
Post a Comment